try_lock_until.pass.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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 recursive_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::recursive_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. assert(m.try_lock());
  31. m.unlock();
  32. m.unlock();
  33. ns d = t1 - t0 - ms(250);
  34. assert(d < ms(50)); // within 50ms
  35. }
  36. void f2()
  37. {
  38. time_point t0 = Clock::now();
  39. assert(m.try_lock_until(Clock::now() + ms(250)) == false);
  40. time_point t1 = Clock::now();
  41. ns d = t1 - t0 - ms(250);
  42. assert(d < ms(50)); // within 50ms
  43. }
  44. int main(int, char**)
  45. {
  46. {
  47. m.lock();
  48. std::thread t(f1);
  49. std::this_thread::sleep_for(ms(250));
  50. m.unlock();
  51. t.join();
  52. }
  53. {
  54. m.lock();
  55. std::thread t(f2);
  56. std::this_thread::sleep_for(ms(300));
  57. m.unlock();
  58. t.join();
  59. }
  60. return 0;
  61. }