try_lock_until_pass.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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 Clock, class Duration>
  16. // bool try_lock_until(const chrono::time_point<Clock, Duration>& abs_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_until(Clock::now() + 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_until(Clock::now() + 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. ns sleep_time = t3 - t2;
  56. ns d_ns = t1 - t0 - sleep_time;
  57. ms d_ms = boost::chrono::duration_cast<boost::chrono::milliseconds>(d_ns);
  58. // BOOST_TEST_GE(d_ms.count(), 0);
  59. BOOST_THREAD_TEST_IT(d_ms, max_diff);
  60. BOOST_THREAD_TEST_IT(d_ns, ns(max_diff));
  61. }
  62. {
  63. m.lock();
  64. boost::thread t(f2);
  65. boost::this_thread::sleep_for(ms(750));
  66. m.unlock();
  67. t.join();
  68. }
  69. return boost::report_errors();
  70. }