Imported Upstream version 1.57.0
[platform/upstream/boost.git] / libs / thread / doc / sync_tutorial.qbk
1 [/
2   (C) Copyright 2012 Vicente J. Botet Escriba.
3   Distributed under the Boost Software License, Version 1.0.
4   (See accompanying file LICENSE_1_0.txt or copy at
5   http://www.boost.org/LICENSE_1_0.txt).
6 ]
7
8 [section:tutorial Tutorial]
9
10 [@http://home.roadrunner.com/~hinnant/mutexes/locking.html Handling mutexes in C++] is an excellent tutorial. You need just replace std and ting by boost.
11
12 [@http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2406.html Mutex, Lock, Condition Variable Rationale] adds rationale for the design decisions made for mutexes, locks and condition variables.
13
14
15 In addition to the C++11 standard locks, Boost.Thread provides other locks and some utilities that help the user to make their code thread-safe.
16
17 [include internal_locking.qbk]
18
19 [include external_locking.qbk]
20
21 [section:with Executing Around a Function]
22
23 In particular, the library provides a way to lock around the execution of a function.
24
25   template <class Lockable, class Function, class... Args>
26   auto with_lock_guard(
27       Lockable& m,
28       Function&& func,
29       Args&&... args
30   ) -> decltype(func(boost::forward<Args>(args)...)) {
31     boost::lock_guard<Lockable> lock(m);
32     return func(boost::forward<Args>(args)...);
33   }
34
35 that can be used with regular functions:
36
37   int func(int, int&);
38   //...
39   boost::mutex m;
40   int a;
41   int result = boost::with_lock_guard(m, func, 1, boost::ref(a));
42
43 with boost::bind:
44
45   int result = boost::with_lock_guard(
46       m, boost::bind(func, 2, boost::ref(a))
47   );
48
49 or with lambda expression:
50
51   int a;
52   int result = boost::with_lock_guard(
53       m,
54       [&a](int x) {
55         // this scope is protected by mutex m
56         a = 3;
57         return x + 4;
58       },
59       5
60   );
61
62 [endsect] [/ With]
63
64 [endsect] [/ Tutorial]