| 1 | #include <boost/thread/thread.hpp>
|
|---|
| 2 | #include <boost/thread/shared_mutex.hpp>
|
|---|
| 3 |
|
|---|
| 4 | #include <iostream>
|
|---|
| 5 |
|
|---|
| 6 | boost::shared_mutex mutex;
|
|---|
| 7 |
|
|---|
| 8 | void thread()
|
|---|
| 9 | {
|
|---|
| 10 | try
|
|---|
| 11 | {
|
|---|
| 12 | for (;;)
|
|---|
| 13 | {
|
|---|
| 14 | boost::system_time timeout = boost::get_system_time() + boost::posix_time::milliseconds(50);
|
|---|
| 15 |
|
|---|
| 16 | if (mutex.timed_lock(timeout))
|
|---|
| 17 | {
|
|---|
| 18 | boost::this_thread::sleep(boost::posix_time::milliseconds(10));
|
|---|
| 19 | mutex.unlock();
|
|---|
| 20 | }
|
|---|
| 21 | }
|
|---|
| 22 | }
|
|---|
| 23 | catch (boost::lock_error& le)
|
|---|
| 24 | {
|
|---|
| 25 | std::cerr << "lock_error exception\n";
|
|---|
| 26 | }
|
|---|
| 27 | }
|
|---|
| 28 |
|
|---|
| 29 | int main()
|
|---|
| 30 | {
|
|---|
| 31 | const int nrThreads = 20;
|
|---|
| 32 | boost::thread* threads[nrThreads];
|
|---|
| 33 |
|
|---|
| 34 | for (int i = 0; i < nrThreads; ++i)
|
|---|
| 35 | threads[i] = new boost::thread(&thread);
|
|---|
| 36 |
|
|---|
| 37 | for (int i = 0; i < nrThreads; ++i)
|
|---|
| 38 | {
|
|---|
| 39 | threads[i]->join();
|
|---|
| 40 | delete threads[i];
|
|---|
| 41 | }
|
|---|
| 42 | return 0;
|
|---|
| 43 | }
|
|---|