try_lock_for_pass.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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) 2012 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/shared_mutex.hpp>
  14. // class shared_mutex;
  15. // template <class Rep, class Period>
  16. // bool try_lock_for(const chrono::duration<Rep, Period>& rel_time);
  17. #include <boost/thread/shared_mutex.hpp>
  18. #include <boost/thread/thread.hpp>
  19. #include <boost/detail/lightweight_test.hpp>
  20. #include "../../../timming.hpp"
  21. boost::shared_mutex m;
  22. typedef boost::chrono::high_resolution_clock Clock;
  23. typedef Clock::time_point time_point;
  24. typedef Clock::duration duration;
  25. typedef boost::chrono::milliseconds ms;
  26. typedef boost::chrono::nanoseconds ns;
  27. time_point t0;
  28. time_point t1;
  29. const ms max_diff(BOOST_THREAD_TEST_TIME_MS);
  30. void f1()
  31. {
  32. t0 = Clock::now();
  33. BOOST_TEST(m.try_lock_for(ms(750)) == true);
  34. t1 = Clock::now();
  35. m.unlock();
  36. }
  37. void f2()
  38. {
  39. t0 = Clock::now();
  40. BOOST_TEST(m.try_lock_for(ms(250)) == false);
  41. t1 = Clock::now();
  42. ns d = t1 - t0 - ms(250);
  43. BOOST_THREAD_TEST_IT(d, ns(max_diff));
  44. }
  45. int main()
  46. {
  47. {
  48. m.lock();
  49. boost::thread t(f1);
  50. time_point t2 = Clock::now();
  51. boost::this_thread::sleep_for(ms(250));
  52. time_point t3 = Clock::now();
  53. m.unlock();
  54. t.join();
  55. #if defined BOOST_THREAD_USES_CHRONO
  56. ns sleep_time = t3 - t2;
  57. ns d_ns = t1 - t0 - sleep_time;
  58. ms d_ms = boost::chrono::duration_cast<boost::chrono::milliseconds>(d_ns);
  59. // BOOST_TEST_GE(d_ms.count(), 0);
  60. BOOST_THREAD_TEST_IT(d_ms, max_diff);
  61. BOOST_THREAD_TEST_IT(d_ns, ns(max_diff));
  62. #endif
  63. }
  64. {
  65. m.lock();
  66. boost::thread t(f2);
  67. boost::this_thread::sleep_for(ms(750));
  68. m.unlock();
  69. t.join();
  70. }
  71. return boost::report_errors();
  72. }