wait_for.pass.cpp 2.0 KB

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