try_lock_until.pass.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. // <mutex>
  11. // class timed_mutex;
  12. // template <class Clock, class Duration>
  13. // bool try_lock_until(const chrono::time_point<Clock, Duration>& abs_time);
  14. #include <mutex>
  15. #include <thread>
  16. #include <cstdlib>
  17. #include <cassert>
  18. #include "test_macros.h"
  19. std::timed_mutex m;
  20. typedef std::chrono::steady_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 f1()
  26. {
  27. time_point t0 = Clock::now();
  28. assert(m.try_lock_until(Clock::now() + ms(300)) == true);
  29. time_point t1 = Clock::now();
  30. m.unlock();
  31. ns d = t1 - t0 - ms(250);
  32. assert(d < ms(50)); // within 50ms
  33. }
  34. void f2()
  35. {
  36. time_point t0 = Clock::now();
  37. assert(m.try_lock_until(Clock::now() + ms(250)) == false);
  38. time_point t1 = Clock::now();
  39. ns d = t1 - t0 - ms(250);
  40. assert(d < ms(50)); // within 50ms
  41. }
  42. int main(int, char**)
  43. {
  44. {
  45. m.lock();
  46. std::thread t(f1);
  47. std::this_thread::sleep_for(ms(250));
  48. m.unlock();
  49. t.join();
  50. }
  51. {
  52. m.lock();
  53. std::thread t(f2);
  54. std::this_thread::sleep_for(ms(300));
  55. m.unlock();
  56. t.join();
  57. }
  58. return 0;
  59. }