Line | |
---|
1 | // Copyright (C) 2001-2003 |
---|
2 | // William E. Kempf |
---|
3 | // |
---|
4 | // Permission to use, copy, modify, distribute and sell this software |
---|
5 | // and its documentation for any purpose is hereby granted without fee, |
---|
6 | // provided that the above copyright notice appear in all copies and |
---|
7 | // that both that copyright notice and this permission notice appear |
---|
8 | // in supporting documentation. William E. Kempf makes no representations |
---|
9 | // about the suitability of this software for any purpose. |
---|
10 | // It is provided "as is" without express or implied warranty. |
---|
11 | |
---|
12 | #include <boost/thread/recursive_mutex.hpp> |
---|
13 | #include <boost/thread/thread.hpp> |
---|
14 | #include <iostream> |
---|
15 | |
---|
16 | class counter |
---|
17 | { |
---|
18 | public: |
---|
19 | counter() : count(0) { } |
---|
20 | |
---|
21 | int add(int val) { |
---|
22 | boost::recursive_mutex::scoped_lock scoped_lock(mutex); |
---|
23 | count += val; |
---|
24 | return count; |
---|
25 | } |
---|
26 | int increment() { |
---|
27 | boost::recursive_mutex::scoped_lock scoped_lock(mutex); |
---|
28 | return add(1); |
---|
29 | } |
---|
30 | |
---|
31 | private: |
---|
32 | boost::recursive_mutex mutex; |
---|
33 | int count; |
---|
34 | }; |
---|
35 | |
---|
36 | counter c; |
---|
37 | |
---|
38 | void change_count() |
---|
39 | { |
---|
40 | std::cout << "count == " << c.increment() << std::endl; |
---|
41 | } |
---|
42 | |
---|
43 | int main(int, char*[]) |
---|
44 | { |
---|
45 | const int num_threads=4; |
---|
46 | |
---|
47 | boost::thread_group threads; |
---|
48 | for (int i=0; i < num_threads; ++i) |
---|
49 | threads.create_thread(&change_count); |
---|
50 | |
---|
51 | threads.join_all(); |
---|
52 | |
---|
53 | return 0; |
---|
54 | } |
---|
Note: See
TracBrowser
for help on using the repository browser.