mutex.pass.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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. // template <class Mutex> class shared_lock;
  15. // explicit shared_lock(mutex_type& m);
  16. // template<class _Mutex> shared_lock(shared_lock<_Mutex>)
  17. // -> shared_lock<_Mutex>; // C++17
  18. #include <shared_mutex>
  19. #include <thread>
  20. #include <vector>
  21. #include <cstdlib>
  22. #include <cassert>
  23. #include "test_macros.h"
  24. typedef std::chrono::system_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. std::shared_timed_mutex m;
  39. void f()
  40. {
  41. time_point t0 = Clock::now();
  42. time_point t1;
  43. {
  44. std::shared_lock<std::shared_timed_mutex> ul(m);
  45. t1 = Clock::now();
  46. }
  47. ns d = t1 - t0 - WaitTime;
  48. assert(d < Tolerance); // within tolerance
  49. }
  50. void g()
  51. {
  52. time_point t0 = Clock::now();
  53. time_point t1;
  54. {
  55. std::shared_lock<std::shared_timed_mutex> ul(m);
  56. t1 = Clock::now();
  57. }
  58. ns d = t1 - t0;
  59. assert(d < Tolerance); // within tolerance
  60. }
  61. int main(int, char**)
  62. {
  63. std::vector<std::thread> v;
  64. {
  65. m.lock();
  66. for (int i = 0; i < 5; ++i)
  67. v.push_back(std::thread(f));
  68. std::this_thread::sleep_for(WaitTime);
  69. m.unlock();
  70. for (auto& t : v)
  71. t.join();
  72. }
  73. {
  74. m.lock_shared();
  75. for (auto& t : v)
  76. t = std::thread(g);
  77. std::thread q(f);
  78. std::this_thread::sleep_for(WaitTime);
  79. m.unlock_shared();
  80. for (auto& t : v)
  81. t.join();
  82. q.join();
  83. }
  84. #ifdef __cpp_deduction_guides
  85. std::shared_lock sl(m);
  86. static_assert((std::is_same<decltype(sl), std::shared_lock<decltype(m)>>::value), "" );
  87. #endif
  88. return 0;
  89. }