lock.pass.cpp 2.1 KB

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