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 | |
7 | // See www.boost.org/libs/thread for documentation. |
8 | |
9 | #define BOOST_THREAD_VERSION 4 |
10 | |
11 | #include <iostream> // std::cout |
12 | #include <boost/thread/scoped_thread.hpp> |
13 | #include <boost/thread/with_lock_guard.hpp> |
14 | |
15 | boost::mutex m; // protection for 'x' and 'std::cout' |
16 | int x; |
17 | |
18 | #if defined(BOOST_NO_CXX11_LAMBDAS) || (defined BOOST_MSVC && _MSC_VER < 1700) |
19 | void print_x() { |
20 | ++x; |
21 | std::cout << "x = " << x << std::endl; |
22 | } |
23 | |
24 | void job() { |
25 | for (int i = 0; i < 10; ++i) { |
26 | boost::with_lock_guard(m, print_x); |
27 | boost::this_thread::sleep_for(boost::chrono::milliseconds(100)); |
28 | } |
29 | } |
30 | #else |
31 | void job() { |
32 | for (int i = 0; i < 10; ++i) { |
33 | boost::with_lock_guard( |
34 | m, |
35 | func: []() { |
36 | ++x; |
37 | std::cout << "x = " << x << std::endl; |
38 | } |
39 | ); |
40 | boost::this_thread::sleep_for(d: boost::chrono::milliseconds(100)); |
41 | } |
42 | } |
43 | #endif |
44 | |
45 | int main() { |
46 | #if defined(BOOST_NO_CXX11_LAMBDAS) || (defined BOOST_MSVC && _MSC_VER < 1700) |
47 | std::cout << "(no lambdas)" << std::endl; |
48 | #endif |
49 | boost::scoped_thread<> thread_1((boost::thread(job))); |
50 | boost::scoped_thread<> thread_2((boost::thread(job))); |
51 | boost::scoped_thread<> thread_3((boost::thread(job))); |
52 | return 0; |
53 | } |
54 | |