test_completion_latch.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. // Distributed under the Boost Software License, Version 1.0. (See
  2. // accompanying file LICENSE_1_0.txt or copy at
  3. // http://www.boost.org/LICENSE_1_0.txt)
  4. // (C) Copyright 2013 Vicente J. Botet Escriba
  5. #define BOOST_THREAD_PROVIDES_INTERRUPTIONS
  6. #include <boost/thread/detail/config.hpp>
  7. #include <boost/thread/thread.hpp>
  8. #include <boost/thread/completion_latch.hpp>
  9. #include <boost/detail/lightweight_test.hpp>
  10. #include <vector>
  11. namespace
  12. {
  13. // Shared variables for generation completion_latch test
  14. const int N_THREADS = 10;
  15. boost::completion_latch gen_latch(N_THREADS);
  16. boost::mutex mutex;
  17. long global_parameter;
  18. void latch_thread()
  19. {
  20. {
  21. boost::unique_lock<boost::mutex> lock(mutex);
  22. global_parameter++;
  23. }
  24. gen_latch.count_down();
  25. //do something else
  26. }
  27. } // namespace
  28. void test_global_parameter()
  29. {
  30. boost::unique_lock<boost::mutex> lock(mutex);
  31. BOOST_TEST_EQ(global_parameter, N_THREADS);
  32. }
  33. void reset_gen_latch()
  34. {
  35. {
  36. boost::unique_lock<boost::mutex> lock(mutex);
  37. BOOST_TEST_EQ(global_parameter, N_THREADS);
  38. }
  39. gen_latch.reset(N_THREADS);
  40. }
  41. void test_completion_latch_reset()
  42. {
  43. boost::thread_group g;
  44. boost::thread_group g2;
  45. gen_latch.then(&reset_gen_latch);
  46. {
  47. global_parameter = 0;
  48. try
  49. {
  50. for (int i = 0; i < N_THREADS; ++i)
  51. g.create_thread(&latch_thread);
  52. if (!gen_latch.try_wait())
  53. if (gen_latch.wait_for(boost::chrono::milliseconds(100)) == boost::cv_status::timeout)
  54. if (gen_latch.wait_until(boost::chrono::steady_clock::now()+boost::chrono::milliseconds(100)) == boost::cv_status::timeout)
  55. gen_latch.wait(); // All the threads have been updated the global_parameter
  56. g.join_all();
  57. }
  58. catch (...)
  59. {
  60. BOOST_TEST(false);
  61. g.interrupt_all();
  62. g.join_all();
  63. //throw;
  64. }
  65. }
  66. gen_latch.then(&test_global_parameter);
  67. {
  68. global_parameter = 0;
  69. try
  70. {
  71. for (int i = 0; i < N_THREADS; ++i)
  72. g2.create_thread(&latch_thread);
  73. if (!gen_latch.try_wait())
  74. gen_latch.wait(); // All the threads have been updated the global_parameter
  75. g2.join_all();
  76. }
  77. catch (...)
  78. {
  79. BOOST_TEST(false);
  80. g2.interrupt_all();
  81. g2.join_all();
  82. //throw;
  83. }
  84. }
  85. }
  86. int main()
  87. {
  88. test_completion_latch_reset();
  89. return boost::report_errors();
  90. }