try_lock_shared.pass.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. // bool try_lock_shared();
  15. #include <shared_mutex>
  16. #include <thread>
  17. #include <vector>
  18. #include <cstdlib>
  19. #include <cassert>
  20. #include "test_macros.h"
  21. std::shared_timed_mutex m;
  22. typedef std::chrono::system_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. #if !defined(TEST_HAS_SANITIZERS)
  28. ms Tolerance = ms(200);
  29. #else
  30. ms Tolerance = ms(200 * 5);
  31. #endif
  32. void f()
  33. {
  34. time_point t0 = Clock::now();
  35. assert(!m.try_lock_shared());
  36. assert(!m.try_lock_shared());
  37. assert(!m.try_lock_shared());
  38. while(!m.try_lock_shared())
  39. ;
  40. time_point t1 = Clock::now();
  41. m.unlock_shared();
  42. ns d = t1 - t0 - ms(250);
  43. assert(d < Tolerance); // within tolerance
  44. }
  45. int main(int, char**)
  46. {
  47. m.lock();
  48. std::vector<std::thread> v;
  49. for (int i = 0; i < 5; ++i)
  50. v.push_back(std::thread(f));
  51. std::this_thread::sleep_for(ms(250));
  52. m.unlock();
  53. for (auto& t : v)
  54. t.join();
  55. return 0;
  56. }