thread_group.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright (C) 2001-2003
  2. // William E. Kempf
  3. //
  4. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  5. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. #include <boost/thread/thread.hpp>
  7. #include <iostream>
  8. #include <boost/detail/lightweight_test.hpp>
  9. int count = 0;
  10. boost::mutex mutex;
  11. void increment_count()
  12. {
  13. boost::unique_lock<boost::mutex> lock(mutex);
  14. std::cout << "count = " << ++count << std::endl;
  15. }
  16. boost::thread_group threads2;
  17. boost::thread* th2 = 0;
  18. void increment_count_2()
  19. {
  20. boost::unique_lock<boost::mutex> lock(mutex);
  21. BOOST_TEST(threads2.is_this_thread_in());
  22. std::cout << "count = " << ++count << std::endl;
  23. }
  24. int main()
  25. {
  26. {
  27. boost::thread_group threads;
  28. for (int i = 0; i < 3; ++i)
  29. threads.create_thread(&increment_count);
  30. threads.join_all();
  31. }
  32. #if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
  33. {
  34. boost::thread_group threads;
  35. for (int i = 0; i < 3; ++i)
  36. threads.create_thread(&increment_count);
  37. threads.interrupt_all();
  38. threads.join_all();
  39. }
  40. #endif
  41. {
  42. boost::thread_group threads;
  43. boost::thread* th = new boost::thread(&increment_count);
  44. threads.add_thread(th);
  45. BOOST_TEST(! threads.is_this_thread_in());
  46. threads.join_all();
  47. }
  48. {
  49. boost::thread_group threads;
  50. boost::thread* th = new boost::thread(&increment_count);
  51. threads.add_thread(th);
  52. BOOST_TEST(threads.is_thread_in(th));
  53. threads.remove_thread(th);
  54. BOOST_TEST(! threads.is_thread_in(th));
  55. th->join();
  56. delete th;
  57. }
  58. {
  59. {
  60. boost::unique_lock<boost::mutex> lock(mutex);
  61. boost::thread* th2 = new boost::thread(&increment_count_2);
  62. threads2.add_thread(th2);
  63. }
  64. threads2.join_all();
  65. }
  66. return boost::report_errors();
  67. }