lock.pass.cpp 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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, c++14
  11. // FLAKY_TEST.
  12. // <shared_mutex>
  13. // class shared_mutex;
  14. // void lock();
  15. #include <shared_mutex>
  16. #include <thread>
  17. #include <cstdlib>
  18. #include <cassert>
  19. #include "test_macros.h"
  20. std::shared_mutex m;
  21. typedef std::chrono::system_clock Clock;
  22. typedef Clock::time_point time_point;
  23. typedef Clock::duration duration;
  24. typedef std::chrono::milliseconds ms;
  25. typedef std::chrono::nanoseconds ns;
  26. ms WaitTime = ms(250);
  27. // Thread sanitizer causes more overhead and will sometimes cause this test
  28. // to fail. To prevent this we give Thread sanitizer more time to complete the
  29. // test.
  30. #if !defined(TEST_HAS_SANITIZERS)
  31. ms Tolerance = ms(50);
  32. #else
  33. ms Tolerance = ms(50 * 5);
  34. #endif
  35. void f()
  36. {
  37. time_point t0 = Clock::now();
  38. m.lock();
  39. time_point t1 = Clock::now();
  40. m.unlock();
  41. ns d = t1 - t0 - WaitTime;
  42. assert(d < Tolerance); // within tolerance
  43. }
  44. int main(int, char**)
  45. {
  46. m.lock();
  47. std::thread t(f);
  48. std::this_thread::sleep_for(WaitTime);
  49. m.unlock();
  50. t.join();
  51. return 0;
  52. }