mutex_time_point.pass.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. // XFAIL: dylib-has-no-shared_mutex
  12. // FLAKY_TEST.
  13. // <shared_mutex>
  14. // class shared_timed_mutex;
  15. // template <class Clock, class Duration>
  16. // shared_lock(mutex_type& m, const chrono::time_point<Clock, Duration>& abs_time);
  17. #include <shared_mutex>
  18. #include <thread>
  19. #include <vector>
  20. #include <cstdlib>
  21. #include <cassert>
  22. #include "test_macros.h"
  23. std::shared_timed_mutex m;
  24. typedef std::chrono::steady_clock Clock;
  25. typedef Clock::time_point time_point;
  26. typedef Clock::duration duration;
  27. typedef std::chrono::milliseconds ms;
  28. typedef std::chrono::nanoseconds ns;
  29. ms WaitTime = ms(250);
  30. // Thread sanitizer causes more overhead and will sometimes cause this test
  31. // to fail. To prevent this we give Thread sanitizer more time to complete the
  32. // test.
  33. #if !defined(TEST_HAS_SANITIZERS)
  34. ms Tolerance = ms(50);
  35. #else
  36. ms Tolerance = ms(50 * 5);
  37. #endif
  38. void f1()
  39. {
  40. time_point t0 = Clock::now();
  41. std::shared_lock<std::shared_timed_mutex> lk(m, Clock::now() + WaitTime + Tolerance);
  42. assert(lk.owns_lock() == true);
  43. time_point t1 = Clock::now();
  44. ns d = t1 - t0 - WaitTime;
  45. assert(d < Tolerance); // within 50ms
  46. }
  47. void f2()
  48. {
  49. time_point t0 = Clock::now();
  50. std::shared_lock<std::shared_timed_mutex> lk(m, Clock::now() + WaitTime);
  51. assert(lk.owns_lock() == false);
  52. time_point t1 = Clock::now();
  53. ns d = t1 - t0 - WaitTime;
  54. assert(d < Tolerance); // within 50ms
  55. }
  56. int main(int, char**)
  57. {
  58. {
  59. m.lock();
  60. std::vector<std::thread> v;
  61. for (int i = 0; i < 5; ++i)
  62. v.push_back(std::thread(f1));
  63. std::this_thread::sleep_for(WaitTime);
  64. m.unlock();
  65. for (auto& t : v)
  66. t.join();
  67. }
  68. {
  69. m.lock();
  70. std::vector<std::thread> v;
  71. for (int i = 0; i < 5; ++i)
  72. v.push_back(std::thread(f2));
  73. std::this_thread::sleep_for(WaitTime + Tolerance);
  74. m.unlock();
  75. for (auto& t : v)
  76. t.join();
  77. }
  78. return 0;
  79. }