wait_for_pred.pass.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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. // <condition_variable>
  11. // class condition_variable;
  12. // template <class Rep, class Period, class Predicate>
  13. // bool
  14. // wait_for(unique_lock<mutex>& lock,
  15. // const chrono::duration<Rep, Period>& rel_time,
  16. // Predicate pred);
  17. #include <condition_variable>
  18. #include <mutex>
  19. #include <thread>
  20. #include <chrono>
  21. #include <cassert>
  22. #include "test_macros.h"
  23. class Pred
  24. {
  25. int& i_;
  26. public:
  27. explicit Pred(int& i) : i_(i) {}
  28. bool operator()() {return i_ != 0;}
  29. };
  30. std::condition_variable cv;
  31. std::mutex mut;
  32. int test1 = 0;
  33. int test2 = 0;
  34. int runs = 0;
  35. void f()
  36. {
  37. typedef std::chrono::system_clock Clock;
  38. typedef std::chrono::milliseconds milliseconds;
  39. std::unique_lock<std::mutex> lk(mut);
  40. assert(test2 == 0);
  41. test1 = 1;
  42. cv.notify_one();
  43. Clock::time_point t0 = Clock::now();
  44. bool r = cv.wait_for(lk, milliseconds(250), Pred(test2));
  45. ((void)r); // Prevent unused warning
  46. Clock::time_point t1 = Clock::now();
  47. if (runs == 0)
  48. {
  49. assert(t1 - t0 < milliseconds(250));
  50. assert(test2 != 0);
  51. }
  52. else
  53. {
  54. assert(t1 - t0 - milliseconds(250) < milliseconds(50));
  55. assert(test2 == 0);
  56. }
  57. ++runs;
  58. }
  59. int main(int, char**)
  60. {
  61. {
  62. std::unique_lock<std::mutex>lk(mut);
  63. std::thread t(f);
  64. assert(test1 == 0);
  65. while (test1 == 0)
  66. cv.wait(lk);
  67. assert(test1 != 0);
  68. test2 = 1;
  69. lk.unlock();
  70. cv.notify_one();
  71. t.join();
  72. }
  73. test1 = 0;
  74. test2 = 0;
  75. {
  76. std::unique_lock<std::mutex>lk(mut);
  77. std::thread t(f);
  78. assert(test1 == 0);
  79. while (test1 == 0)
  80. cv.wait(lk);
  81. assert(test1 != 0);
  82. lk.unlock();
  83. t.join();
  84. }
  85. return 0;
  86. }