Ticket #9058: with_lock_guard_example.cpp

File with_lock_guard_example.cpp, 809 bytes (added by ruslan_baratov@…, 9 years ago)

example

Line 
1// (C) Copyright 2013 Ruslan Baratov
2//
3// Distributed under the Boost Software License, Version 1.0. (See accompanying
4// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
5
6// See www.boost.org/libs/thread for documentation.
7
8#include <iostream>
9#include <boost/thread/scoped_thread.hpp>
10#include <boost/thread/with_lock_guard.hpp>
11
12boost::mutex m; // protection for 'x' and 'std::cout'
13int x;
14
15void job() {
16 for (int i = 0; i < 10; ++i) {
17 boost::with_lock_guard(
18 m,
19 []() {
20 ++x;
21 std::cout << "x = " << x << std::endl;
22 }
23 );
24 boost::this_thread::sleep_for(boost::chrono::milliseconds(100));
25 }
26}
27
28int main() {
29 boost::scoped_thread<> thread_1(job);
30 boost::scoped_thread<> thread_2(job);
31 boost::scoped_thread<> thread_3(job);
32}