sync_tutorial.qbk 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. [section:tutorial Tutorial]
  8. [@http://web.archive.org/web/20140531071228/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.
  9. [@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.
  10. 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.
  11. [include internal_locking.qbk]
  12. [include external_locking.qbk]
  13. [section:with Executing Around a Function]
  14. In particular, the library provides a way to lock around the execution of a function.
  15. template <class Lockable, class Function, class... Args>
  16. auto with_lock_guard(
  17. Lockable& m,
  18. Function&& func,
  19. Args&&... args
  20. ) -> decltype(func(boost::forward<Args>(args)...)) {
  21. boost::lock_guard<Lockable> lock(m);
  22. return func(boost::forward<Args>(args)...);
  23. }
  24. that can be used with regular functions:
  25. int func(int, int&);
  26. //...
  27. boost::mutex m;
  28. int a;
  29. int result = boost::with_lock_guard(m, func, 1, boost::ref(a));
  30. with boost::bind:
  31. int result = boost::with_lock_guard(
  32. m, boost::bind(func, 2, boost::ref(a))
  33. );
  34. or with lambda expression:
  35. int a;
  36. int result = boost::with_lock_guard(
  37. m,
  38. [&a](int x) {
  39. // this scope is protected by mutex m
  40. a = 3;
  41. return x + 4;
  42. },
  43. 5
  44. );
  45. [endsect] [/ With]
  46. [endsect] [/ Tutorial]