#include #include #include typedef boost::shared_ptr ThreadPtr; typedef std::vector Threads; typedef Threads::size_type ThreadsSize; class Test { public: Test(ThreadsSize threads_count): m_threads_count(threads_count) { } class Job { public: Job(size_t id, Test& test) : m_id(id), m_test(test) { } void operator()() { try { std::cout << boost::format("thread %d started\n") % m_id; boost::unique_lock lock(m_test.m_lock); std::cout << boost::format("thread %d locked\n") % m_id; m_test.m_cv.wait(lock); std::cout << boost::format("thread %d ended without interrupt\n") % m_id; } catch (boost::thread_interrupted) { std::cout << boost::format("thread %d interrupted\n") % m_id; } } private: size_t m_id; Test& m_test; }; void operator()() { for (ThreadsSize i = 0; i < m_threads_count; ++i) { ThreadPtr t(new boost::thread(Job(i, *this))); m_threads.push_back(t); } // wait until all threads are waiting, unsave! boost::this_thread::sleep(boost::posix_time::seconds(1)); for (ThreadsSize i = 0; i < m_threads.size(); ++i) { std::cout << boost::format("thread %d interrupt\n") % i; m_threads[i]->interrupt(); } for (ThreadsSize i = 0; i < m_threads.size(); ++i) { m_threads[i]->join(); std::cout << boost::format("thread %d joined\n") % i; } } private: mutable boost::mutex m_lock; mutable boost::condition_variable m_cv; Threads m_threads; ThreadsSize m_threads_count; }; int main(int argc, char *argv[]) { ThreadsSize threads_count = 10; if (argc > 1) threads_count = atoi(argv[1]); Test test(threads_count); test(); return 0; };