| 1 | #include <iostream>
|
|---|
| 2 |
|
|---|
| 3 | #include <boost/format.hpp>
|
|---|
| 4 | #include <boost/thread.hpp>
|
|---|
| 5 |
|
|---|
| 6 |
|
|---|
| 7 | typedef boost::shared_ptr<boost::thread> ThreadPtr;
|
|---|
| 8 | typedef std::vector<ThreadPtr> Threads;
|
|---|
| 9 | typedef Threads::size_type ThreadsSize;
|
|---|
| 10 |
|
|---|
| 11 | class Test
|
|---|
| 12 | {
|
|---|
| 13 | public:
|
|---|
| 14 | Test(ThreadsSize threads_count):
|
|---|
| 15 | m_threads_count(threads_count)
|
|---|
| 16 | { }
|
|---|
| 17 |
|
|---|
| 18 |
|
|---|
| 19 | class Job
|
|---|
| 20 | {
|
|---|
| 21 | public:
|
|---|
| 22 | Job(size_t id, Test& test) : m_id(id), m_test(test)
|
|---|
| 23 | { }
|
|---|
| 24 |
|
|---|
| 25 |
|
|---|
| 26 | void operator()()
|
|---|
| 27 | {
|
|---|
| 28 | try
|
|---|
| 29 | {
|
|---|
| 30 | std::cout << boost::format("thread %d started\n") % m_id;
|
|---|
| 31 | boost::unique_lock<boost::mutex> lock(m_test.m_lock);
|
|---|
| 32 | std::cout << boost::format("thread %d locked\n") % m_id;
|
|---|
| 33 | m_test.m_cv.wait(lock);
|
|---|
| 34 | std::cout << boost::format("thread %d ended without interrupt\n") % m_id;
|
|---|
| 35 | }
|
|---|
| 36 | catch (boost::thread_interrupted)
|
|---|
| 37 | {
|
|---|
| 38 | std::cout << boost::format("thread %d interrupted\n") % m_id;
|
|---|
| 39 | }
|
|---|
| 40 | }
|
|---|
| 41 | private:
|
|---|
| 42 | size_t m_id;
|
|---|
| 43 | Test& m_test;
|
|---|
| 44 | };
|
|---|
| 45 |
|
|---|
| 46 | void operator()()
|
|---|
| 47 | {
|
|---|
| 48 | for (ThreadsSize i = 0; i < m_threads_count; ++i)
|
|---|
| 49 | {
|
|---|
| 50 | ThreadPtr t(new boost::thread(Job(i, *this)));
|
|---|
| 51 | m_threads.push_back(t);
|
|---|
| 52 | }
|
|---|
| 53 |
|
|---|
| 54 | // wait until all threads are waiting, unsave!
|
|---|
| 55 | boost::this_thread::sleep(boost::posix_time::seconds(1));
|
|---|
| 56 |
|
|---|
| 57 | for (ThreadsSize i = 0; i < m_threads.size(); ++i)
|
|---|
| 58 | {
|
|---|
| 59 | std::cout << boost::format("thread %d interrupt\n") % i;
|
|---|
| 60 | m_threads[i]->interrupt();
|
|---|
| 61 | }
|
|---|
| 62 |
|
|---|
| 63 | for (ThreadsSize i = 0; i < m_threads.size(); ++i)
|
|---|
| 64 | {
|
|---|
| 65 | m_threads[i]->join();
|
|---|
| 66 | std::cout << boost::format("thread %d joined\n") % i;
|
|---|
| 67 | }
|
|---|
| 68 | }
|
|---|
| 69 |
|
|---|
| 70 | private:
|
|---|
| 71 | mutable boost::mutex m_lock;
|
|---|
| 72 | mutable boost::condition_variable m_cv;
|
|---|
| 73 | Threads m_threads;
|
|---|
| 74 | ThreadsSize m_threads_count;
|
|---|
| 75 | };
|
|---|
| 76 |
|
|---|
| 77 | int main(int argc, char *argv[])
|
|---|
| 78 | {
|
|---|
| 79 | ThreadsSize threads_count = 10;
|
|---|
| 80 | if (argc > 1)
|
|---|
| 81 | threads_count = atoi(argv[1]);
|
|---|
| 82 |
|
|---|
| 83 | Test test(threads_count);
|
|---|
| 84 | test();
|
|---|
| 85 |
|
|---|
| 86 | return 0;
|
|---|
| 87 | };
|
|---|