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