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; 16 17 // template <class Rep, class Period> 18 // cv_status 19 // wait_for(unique_lock<mutex>& lock, 20 // const chrono::duration<Rep, Period>& rel_time); 21 22 #include <condition_variable> 23 #include <mutex> 24 #include <thread> 25 #include <chrono> 26 #include <cassert> 27 28 #include "make_test_thread.h" 29 #include "test_macros.h" 30 31 std::condition_variable cv; 32 std::mutex mut; 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 std::unique_lock<std::mutex> lk(mut); 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 std::unique_lock<std::mutex> lk(mut); 69 std::thread t = support::make_test_thread(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 std::unique_lock<std::mutex> lk(mut); 83 std::thread t = support::make_test_thread(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