Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: downloads/boost_1_34_1/libs/thread/example/mutex.cpp @ 33

Last change on this file since 33 was 29, checked in by landauf, 16 years ago

updated boost from 1_33_1 to 1_34_1

File size: 965 bytes
Line 
1// Copyright (C) 2001-2003
2// William E. Kempf
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#include <boost/thread/mutex.hpp>
8#include <boost/thread/thread.hpp>
9#include <iostream>
10
11boost::mutex io_mutex; // The iostreams are not guaranteed to be thread-safe!
12
13class counter
14{
15public:
16    counter() : count(0) { }
17
18    int increment() {
19        boost::mutex::scoped_lock scoped_lock(mutex);
20        return ++count;
21    }
22
23private:
24    boost::mutex mutex;
25    int count;
26};
27
28counter c;
29
30void change_count()
31{
32    int i = c.increment();
33    boost::mutex::scoped_lock scoped_lock(io_mutex);
34    std::cout << "count == " << i << std::endl;
35}
36
37int main(int, char*[])
38{
39    const int num_threads = 4;
40    boost::thread_group thrds;
41    for (int i=0; i < num_threads; ++i)
42        thrds.create_thread(&change_count);
43
44    thrds.join_all();
45
46    return 0;
47}
Note: See TracBrowser for help on using the repository browser.