condition_test_common.hpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. #ifndef CONDITION_TEST_COMMON_HPP
  2. #define CONDITION_TEST_COMMON_HPP
  3. // Copyright (C) 2007 Anthony Williams
  4. //
  5. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  6. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  7. #include <boost/thread/condition_variable.hpp>
  8. #include <boost/thread/mutex.hpp>
  9. #include <boost/thread/thread_time.hpp>
  10. unsigned const timeout_seconds=5;
  11. struct wait_for_flag
  12. {
  13. boost::mutex mutex;
  14. boost::condition_variable cond_var;
  15. bool flag;
  16. unsigned woken;
  17. wait_for_flag():
  18. flag(false),woken(0)
  19. {}
  20. struct check_flag
  21. {
  22. bool const& flag;
  23. check_flag(bool const& flag_):
  24. flag(flag_)
  25. {}
  26. bool operator()() const
  27. {
  28. return flag;
  29. }
  30. private:
  31. void operator=(check_flag&);
  32. };
  33. void wait_without_predicate()
  34. {
  35. boost::unique_lock<boost::mutex> lock(mutex);
  36. while(!flag)
  37. {
  38. cond_var.wait(lock);
  39. }
  40. ++woken;
  41. }
  42. void wait_with_predicate()
  43. {
  44. boost::unique_lock<boost::mutex> lock(mutex);
  45. cond_var.wait(lock,check_flag(flag));
  46. if(flag)
  47. {
  48. ++woken;
  49. }
  50. }
  51. void timed_wait_without_predicate()
  52. {
  53. boost::system_time const timeout=boost::get_system_time()+boost::posix_time::seconds(timeout_seconds);
  54. boost::unique_lock<boost::mutex> lock(mutex);
  55. while(!flag)
  56. {
  57. if(!cond_var.timed_wait(lock,timeout))
  58. {
  59. return;
  60. }
  61. }
  62. ++woken;
  63. }
  64. void timed_wait_with_predicate()
  65. {
  66. boost::system_time const timeout=boost::get_system_time()+boost::posix_time::seconds(timeout_seconds);
  67. boost::unique_lock<boost::mutex> lock(mutex);
  68. if(cond_var.timed_wait(lock,timeout,check_flag(flag)) && flag)
  69. {
  70. ++woken;
  71. }
  72. }
  73. void relative_timed_wait_with_predicate()
  74. {
  75. boost::unique_lock<boost::mutex> lock(mutex);
  76. if(cond_var.timed_wait(lock,boost::posix_time::seconds(timeout_seconds),check_flag(flag)) && flag)
  77. {
  78. ++woken;
  79. }
  80. }
  81. };
  82. #endif