test_5502.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. // bm.cpp
  6. // g++ test.cpp -lboost_thread-mt && ./a.out
  7. // the ration of XXX and YYY determines
  8. // if this works or deadlocks
  9. int XXX = 20;
  10. int YYY = 10;
  11. #include <boost/thread/thread_only.hpp>
  12. #include <boost/thread/shared_mutex.hpp>
  13. //#include <unistd.h>
  14. #include <iostream>
  15. #include <boost/detail/lightweight_test.hpp>
  16. using namespace std;
  17. //void sleepmillis(useconds_t miliis)
  18. void sleepmillis(int miliis)
  19. {
  20. //usleep(miliis * 1000);
  21. boost::this_thread::sleep(boost::posix_time::milliseconds(miliis));
  22. }
  23. void worker1(boost::shared_mutex * lk, int * x)
  24. {
  25. (*x)++; // 1
  26. cout << "lock b try " << *x << endl;
  27. while (1)
  28. {
  29. if (lk->timed_lock(boost::posix_time::milliseconds(XXX))) break;
  30. sleepmillis(YYY);
  31. }
  32. cout << "lock b got " << *x << endl;
  33. (*x)++; // 2
  34. lk->unlock();
  35. }
  36. void worker2(boost::shared_mutex * lk, int * x)
  37. {
  38. cout << "lock c try" << endl;
  39. lk->lock_shared();
  40. (*x)++;
  41. cout << "lock c got" << endl;
  42. lk->unlock_shared();
  43. cout << "lock c unlocked" << endl;
  44. (*x)++;
  45. }
  46. int main()
  47. {
  48. // create
  49. boost::shared_mutex* lk = new boost::shared_mutex();
  50. // read lock
  51. cout << "lock a" << endl;
  52. lk->lock_shared();
  53. int x1 = 0;
  54. boost::thread t1(boost::bind(worker1, lk, &x1));
  55. while (!x1)
  56. ;
  57. BOOST_TEST(x1 == 1);
  58. sleepmillis(500);
  59. BOOST_TEST(x1 == 1);
  60. int x2 = 0;
  61. boost::thread t2(boost::bind(worker2, lk, &x2));
  62. t2.join();
  63. BOOST_TEST(x2 == 2);
  64. lk->unlock_shared();
  65. cout << "unlock a" << endl;
  66. for (int i = 0; i < 2000; i++)
  67. {
  68. if (x1 == 2) break;
  69. sleepmillis(10);
  70. }
  71. BOOST_TEST(x1 == 2);
  72. t1.join();
  73. delete lk;
  74. return 0;
  75. }