try_lock_until.pass.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. //===----------------------------------------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // UNSUPPORTED: libcpp-has-no-threads
  10. // UNSUPPORTED: c++98, c++03, c++11
  11. // FLAKY_TEST.
  12. // <shared_mutex>
  13. // class shared_timed_mutex;
  14. // template <class Clock, class Duration>
  15. // bool try_lock_until(const chrono::time_point<Clock, Duration>& abs_time);
  16. #include <shared_mutex>
  17. #include <thread>
  18. #include <cstdlib>
  19. #include <cassert>
  20. #include "test_macros.h"
  21. std::shared_timed_mutex m;
  22. typedef std::chrono::steady_clock Clock;
  23. typedef Clock::time_point time_point;
  24. typedef Clock::duration duration;
  25. typedef std::chrono::milliseconds ms;
  26. typedef std::chrono::nanoseconds ns;
  27. ms WaitTime = ms(250);
  28. // Thread sanitizer causes more overhead and will sometimes cause this test
  29. // to fail. To prevent this we give Thread sanitizer more time to complete the
  30. // test.
  31. #if !defined(TEST_HAS_SANITIZERS)
  32. ms Tolerance = ms(50);
  33. #else
  34. ms Tolerance = ms(50 * 5);
  35. #endif
  36. void f1()
  37. {
  38. time_point t0 = Clock::now();
  39. assert(m.try_lock_until(Clock::now() + WaitTime + Tolerance) == true);
  40. time_point t1 = Clock::now();
  41. m.unlock();
  42. ns d = t1 - t0 - WaitTime;
  43. assert(d < Tolerance); // within tolerance
  44. }
  45. void f2()
  46. {
  47. time_point t0 = Clock::now();
  48. assert(m.try_lock_until(Clock::now() + WaitTime) == false);
  49. time_point t1 = Clock::now();
  50. ns d = t1 - t0 - WaitTime;
  51. assert(d < Tolerance); // within tolerance
  52. }
  53. int main(int, char**)
  54. {
  55. {
  56. m.lock();
  57. std::thread t(f1);
  58. std::this_thread::sleep_for(WaitTime);
  59. m.unlock();
  60. t.join();
  61. }
  62. {
  63. m.lock();
  64. std::thread t(f2);
  65. std::this_thread::sleep_for(WaitTime + Tolerance);
  66. m.unlock();
  67. t.join();
  68. }
  69. return 0;
  70. }