with_lock_guard.cpp 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // (C) Copyright 2013 Ruslan Baratov
  2. // Copyright (C) 2014 Vicente Botet
  3. //
  4. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  5. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. // See www.boost.org/libs/thread for documentation.
  7. #define BOOST_THREAD_VERSION 4
  8. #include <iostream> // std::cout
  9. #include <boost/thread/scoped_thread.hpp>
  10. #include <boost/thread/with_lock_guard.hpp>
  11. boost::mutex m; // protection for 'x' and 'std::cout'
  12. int x;
  13. #if defined(BOOST_NO_CXX11_LAMBDAS) || (defined BOOST_MSVC && _MSC_VER < 1700)
  14. void print_x() {
  15. ++x;
  16. std::cout << "x = " << x << std::endl;
  17. }
  18. void job() {
  19. for (int i = 0; i < 10; ++i) {
  20. boost::with_lock_guard(m, print_x);
  21. boost::this_thread::sleep_for(boost::chrono::milliseconds(100));
  22. }
  23. }
  24. #else
  25. void job() {
  26. for (int i = 0; i < 10; ++i) {
  27. boost::with_lock_guard(
  28. m,
  29. []() {
  30. ++x;
  31. std::cout << "x = " << x << std::endl;
  32. }
  33. );
  34. boost::this_thread::sleep_for(boost::chrono::milliseconds(100));
  35. }
  36. }
  37. #endif
  38. int main() {
  39. #if defined(BOOST_NO_CXX11_LAMBDAS) || (defined BOOST_MSVC && _MSC_VER < 1700)
  40. std::cout << "(no lambdas)" << std::endl;
  41. #endif
  42. boost::scoped_thread<> thread_1((boost::thread(job)));
  43. boost::scoped_thread<> thread_2((boost::thread(job)));
  44. boost::scoped_thread<> thread_3((boost::thread(job)));
  45. return 0;
  46. }