try_lock_pass.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. //===----------------------------------------------------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is dual licensed under the MIT and the University of Illinois Open
  6. // Source Licenses. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. // Copyright (C) 2011 Vicente J. Botet Escriba
  10. //
  11. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  12. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  13. // <boost/thread/recursive_mutex.hpp>
  14. // class recursive_mutex;
  15. // bool try_lock();
  16. #include <boost/thread/recursive_mutex.hpp>
  17. #include <boost/thread/thread.hpp>
  18. #include <boost/detail/lightweight_test.hpp>
  19. #include <iostream>
  20. #include "../../../timming.hpp"
  21. boost::recursive_mutex m;
  22. #if defined BOOST_THREAD_USES_CHRONO
  23. typedef boost::chrono::high_resolution_clock Clock;
  24. typedef Clock::time_point time_point;
  25. typedef Clock::duration duration;
  26. typedef boost::chrono::milliseconds ms;
  27. typedef boost::chrono::nanoseconds ns;
  28. time_point t0;
  29. time_point t1;
  30. #else
  31. #endif
  32. const ms max_diff(BOOST_THREAD_TEST_TIME_MS);
  33. void f()
  34. {
  35. #if defined BOOST_THREAD_USES_CHRONO
  36. t0 = Clock::now();
  37. // BOOST_TEST(!m.try_lock());
  38. // BOOST_TEST(!m.try_lock());
  39. // BOOST_TEST(!m.try_lock());
  40. while (!m.try_lock())
  41. ;
  42. t1 = Clock::now();
  43. BOOST_TEST(m.try_lock());
  44. m.unlock();
  45. m.unlock();
  46. #else
  47. //time_point t0 = Clock::now();
  48. //BOOST_TEST(!m.try_lock());
  49. //BOOST_TEST(!m.try_lock());
  50. //BOOST_TEST(!m.try_lock());
  51. while (!m.try_lock())
  52. ;
  53. //time_point t1 = Clock::now();
  54. BOOST_TEST(m.try_lock());
  55. m.unlock();
  56. m.unlock();
  57. //ns d = t1 - t0 - ms(250);
  58. //BOOST_TEST(d < max_diff);
  59. #endif
  60. }
  61. int main()
  62. {
  63. m.lock();
  64. boost::thread t(f);
  65. #if defined BOOST_THREAD_USES_CHRONO
  66. time_point t2 = Clock::now();
  67. boost::this_thread::sleep_for(ms(250));
  68. time_point t3 = Clock::now();
  69. #else
  70. #endif
  71. m.unlock();
  72. t.join();
  73. #if defined BOOST_THREAD_USES_CHRONO
  74. ns sleep_time = t3 - t2;
  75. ns d_ns = t1 - t0 - sleep_time;
  76. ms d_ms = boost::chrono::duration_cast<boost::chrono::milliseconds>(d_ns);
  77. // BOOST_TEST_GE(d_ms.count(), 0);
  78. BOOST_THREAD_TEST_IT(d_ms, max_diff);
  79. BOOST_THREAD_TEST_IT(d_ns, ns(max_diff));
  80. #endif
  81. return boost::report_errors();
  82. }