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