test_latch.cpp 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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/latch.hpp>
  9. #include <boost/detail/lightweight_test.hpp>
  10. #include <vector>
  11. namespace
  12. {
  13. // Shared variables for generation latch test
  14. const int N_THREADS = 10;
  15. boost::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_latch()
  29. {
  30. boost::thread_group g;
  31. global_parameter = 0;
  32. try
  33. {
  34. for (int i = 0; i < N_THREADS; ++i)
  35. g.create_thread(&latch_thread);
  36. if (! gen_latch.try_wait())
  37. if (gen_latch.wait_for(boost::chrono::milliseconds(100)) == boost::cv_status::timeout)
  38. if (gen_latch.wait_until(boost::chrono::steady_clock::now()+boost::chrono::milliseconds(100)) == boost::cv_status::timeout)
  39. gen_latch.wait(); // All the threads have been updated the global_parameter
  40. BOOST_TEST_EQ(global_parameter, N_THREADS);
  41. g.join_all();
  42. }
  43. catch (...)
  44. {
  45. BOOST_TEST(false);
  46. g.interrupt_all();
  47. g.join_all();
  48. //throw;
  49. }
  50. }
  51. int main()
  52. {
  53. test_latch();
  54. return boost::report_errors();
  55. }