try_lock.pass.cpp 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. // <shared_mutex>
  12. // class shared_timed_mutex;
  13. // bool try_lock();
  14. #include <shared_mutex>
  15. #include <thread>
  16. #include <cstdlib>
  17. #include <cassert>
  18. #include "test_macros.h"
  19. std::shared_timed_mutex m;
  20. typedef std::chrono::system_clock Clock;
  21. typedef Clock::time_point time_point;
  22. typedef Clock::duration duration;
  23. typedef std::chrono::milliseconds ms;
  24. typedef std::chrono::nanoseconds ns;
  25. void f()
  26. {
  27. time_point t0 = Clock::now();
  28. assert(!m.try_lock());
  29. assert(!m.try_lock());
  30. assert(!m.try_lock());
  31. while(!m.try_lock())
  32. ;
  33. time_point t1 = Clock::now();
  34. m.unlock();
  35. ns d = t1 - t0 - ms(250);
  36. assert(d < ms(200)); // within 200ms
  37. }
  38. int main(int, char**)
  39. {
  40. m.lock();
  41. std::thread t(f);
  42. std::this_thread::sleep_for(ms(250));
  43. m.unlock();
  44. t.join();
  45. return 0;
  46. }