try_lock_until_pass.cpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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>
  14. // class recursive_timed_mutex;
  15. // template <class Clock, class Duration>
  16. // bool try_lock_until(const chrono::time_point<Clock, Duration>& abs_time);
  17. #include <boost/thread/recursive_mutex.hpp>
  18. #include <boost/thread/thread.hpp>
  19. #include <boost/detail/lightweight_test.hpp>
  20. #include "../../../timming.hpp"
  21. #if defined BOOST_THREAD_USES_CHRONO
  22. boost::recursive_timed_mutex m;
  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. const ms max_diff(BOOST_THREAD_TEST_TIME_MS);
  31. void f1()
  32. {
  33. t0 = Clock::now();
  34. BOOST_TEST(m.try_lock_until(Clock::now() + ms(750)) == true);
  35. t1 = Clock::now();
  36. m.unlock();
  37. }
  38. void f2()
  39. {
  40. t0 = Clock::now();
  41. BOOST_TEST(m.try_lock_until(Clock::now() + ms(250)) == false);
  42. t1 = Clock::now();
  43. ns d = t1 - t0 - ms(250);
  44. BOOST_THREAD_TEST_IT(d, ns(max_diff));
  45. }
  46. int main()
  47. {
  48. {
  49. m.lock();
  50. boost::thread t(f1);
  51. time_point t2 = Clock::now();
  52. boost::this_thread::sleep_for(ms(250));
  53. time_point t3 = Clock::now();
  54. m.unlock();
  55. t.join();
  56. #if defined BOOST_THREAD_USES_CHRONO
  57. ns sleep_time = t3 - t2;
  58. ns d_ns = t1 - t0 - sleep_time;
  59. ms d_ms = boost::chrono::duration_cast<boost::chrono::milliseconds>(d_ns);
  60. // BOOST_TEST_GE(d_ms.count(), 0);
  61. BOOST_THREAD_TEST_IT(d_ms, max_diff);
  62. BOOST_THREAD_TEST_IT(d_ns, ns(max_diff));
  63. #endif
  64. }
  65. {
  66. m.lock();
  67. boost::thread t(f2);
  68. boost::this_thread::sleep_for(ms(750));
  69. m.unlock();
  70. t.join();
  71. }
  72. return boost::report_errors();
  73. }
  74. #else
  75. #error "Test not applicable: BOOST_THREAD_USES_CHRONO not defined for this platform as not supported"
  76. #endif