try_lock_pass.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. // bool try_lock();
  16. #include <boost/thread/shared_mutex.hpp>
  17. #include <boost/thread/thread.hpp>
  18. #include <boost/detail/lightweight_test.hpp>
  19. #include "../../../timming.hpp"
  20. boost::shared_mutex m;
  21. #if defined BOOST_THREAD_USES_CHRONO
  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. #else
  30. #endif
  31. const ms max_diff(BOOST_THREAD_TEST_TIME_MS);
  32. void f()
  33. {
  34. #if defined BOOST_THREAD_USES_CHRONO
  35. t0 = Clock::now();
  36. BOOST_TEST(!m.try_lock());
  37. BOOST_TEST(!m.try_lock());
  38. BOOST_TEST(!m.try_lock());
  39. while (!m.try_lock())
  40. ;
  41. t1 = Clock::now();
  42. m.unlock();
  43. #else
  44. //time_point t0 = Clock::now();
  45. //BOOST_TEST(!m.try_lock());
  46. //BOOST_TEST(!m.try_lock());
  47. //BOOST_TEST(!m.try_lock());
  48. while (!m.try_lock())
  49. ;
  50. //time_point t1 = Clock::now();
  51. m.unlock();
  52. //ns d = t1 - t0 - ms(250);
  53. //BOOST_TEST(d < max_diff);
  54. #endif
  55. }
  56. int main()
  57. {
  58. m.lock();
  59. boost::thread t(f);
  60. #if defined BOOST_THREAD_USES_CHRONO
  61. time_point t2 = Clock::now();
  62. boost::this_thread::sleep_for(ms(250));
  63. time_point t3 = Clock::now();
  64. #else
  65. #endif
  66. m.unlock();
  67. t.join();
  68. #if defined BOOST_THREAD_USES_CHRONO
  69. ns sleep_time = t3 - t2;
  70. ns d_ns = t1 - t0 - sleep_time;
  71. ms d_ms = boost::chrono::duration_cast<boost::chrono::milliseconds>(d_ns);
  72. // BOOST_TEST_GE(d_ms.count(), 0);
  73. BOOST_THREAD_TEST_IT(d_ms, max_diff);
  74. BOOST_THREAD_TEST_IT(d_ns, ns(max_diff));
  75. #endif
  76. return boost::report_errors();
  77. }