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