test_3628.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. // Copyright (C) 2010 Vicente Botet
  2. //
  3. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  4. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  5. #define BOOST_THREAD_VERSION 2
  6. #include <boost/thread/thread.hpp>
  7. #include <boost/thread/condition.hpp>
  8. #include <boost/thread/recursive_mutex.hpp>
  9. #include <list>
  10. #include <iostream>
  11. #if defined BOOST_THREAD_USES_CHRONO
  12. using namespace std;
  13. boost::recursive_mutex theMutex;
  14. typedef std::list<boost::condition*> Conditions;
  15. Conditions theConditions;
  16. void ThreadFuncWaiter()
  17. {
  18. boost::condition con1;
  19. //for(; ; )
  20. for (int j = 0; j < 10; j++)
  21. {
  22. {
  23. boost::unique_lock<boost::recursive_mutex> lockMtx(theMutex);
  24. theConditions.push_back(&con1);
  25. cout << "Added " << boost::this_thread::get_id() << " " << &con1 << endl;
  26. if (con1.timed_wait(lockMtx, boost::posix_time::time_duration(0, 0, 50)))
  27. {
  28. cout << "Woke Up " << boost::this_thread::get_id() << " " << &con1 << endl;
  29. }
  30. else
  31. {
  32. cout << "*****Timed Out " << boost::this_thread::get_id() << " " << &con1 << endl;
  33. exit(13);
  34. }
  35. theConditions.remove(&con1);
  36. cout << "Removed " << boost::this_thread::get_id() << " " << &con1 << endl;
  37. cout << "Waiter " << j << endl;
  38. }
  39. //Sleep(2000);
  40. boost::this_thread::sleep_for(boost::chrono::milliseconds(200));
  41. }
  42. }
  43. void ThreadFuncNotifier()
  44. {
  45. for (int j = 0; j < 70; j++)
  46. {
  47. {
  48. boost::unique_lock<boost::recursive_mutex> lockMtx(theMutex);
  49. cout << "<Notifier " << j << endl;
  50. unsigned int i = 0;
  51. for (Conditions::iterator it = theConditions.begin(); it != theConditions.end() && i < 2; ++it)
  52. {
  53. (*it)->notify_one();
  54. //WORKAROUND_ lockMtx.unlock();
  55. //WORKAROUND_ boost::this_thread::sleep_for(boost::chrono::milliseconds(50));
  56. cout << "Notified One " << theConditions.size() << " " << (*it) << endl;
  57. ++i;
  58. //WORKAROUND_ lockMtx.lock();
  59. }
  60. cout << "Notifier> " << j << endl;
  61. }
  62. boost::this_thread::sleep_for(boost::chrono::milliseconds(50));
  63. }
  64. }
  65. int main()
  66. {
  67. boost::thread_group tg;
  68. for (int i = 0; i < 12; ++i)
  69. {
  70. tg.create_thread(ThreadFuncWaiter);
  71. }
  72. tg.create_thread(ThreadFuncNotifier);
  73. tg.join_all();
  74. return 0;
  75. }
  76. #else
  77. #error "Test not applicable: BOOST_THREAD_USES_CHRONO not defined for this platform as not supported"
  78. #endif