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