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 // ALLOW_RETRIES: 2 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 #include "test_macros.h" 28 29 std::condition_variable_any cv; 30 31 typedef std::timed_mutex L0; 32 typedef std::unique_lock<L0> L1; 33 34 L0 m0; 35 36 int test1 = 0; 37 int test2 = 0; 38 39 int runs = 0; 40 41 void f() 42 { 43 typedef std::chrono::system_clock Clock; 44 typedef std::chrono::milliseconds milliseconds; 45 L1 lk(m0); 46 assert(test2 == 0); 47 test1 = 1; 48 cv.notify_one(); 49 Clock::time_point t0 = Clock::now(); 50 while (test2 == 0 && 51 cv.wait_for(lk, milliseconds(250)) == std::cv_status::no_timeout) 52 ; 53 Clock::time_point t1 = Clock::now(); 54 if (runs == 0) 55 { 56 assert(t1 - t0 < milliseconds(250)); 57 assert(test2 != 0); 58 } 59 else 60 { 61 assert(t1 - t0 - milliseconds(250) < milliseconds(50)); 62 assert(test2 == 0); 63 } 64 ++runs; 65 } 66 67 int main(int, char**) 68 { 69 { 70 L1 lk(m0); 71 std::thread t(f); 72 assert(test1 == 0); 73 while (test1 == 0) 74 cv.wait(lk); 75 assert(test1 != 0); 76 test2 = 1; 77 lk.unlock(); 78 cv.notify_one(); 79 t.join(); 80 } 81 test1 = 0; 82 test2 = 0; 83 { 84 L1 lk(m0); 85 std::thread t(f); 86 assert(test1 == 0); 87 while (test1 == 0) 88 cv.wait(lk); 89 assert(test1 != 0); 90 lk.unlock(); 91 t.join(); 92 } 93 94 return 0; 95 } 96