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: no-threads 10 // ALLOW_RETRIES: 2 11 12 // <condition_variable> 13 14 // class condition_variable; 15 16 // template <class Rep, class Period> 17 // cv_status 18 // wait_for(unique_lock<mutex>& lock, 19 // 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 "make_test_thread.h" 28 #include "test_macros.h" 29 30 std::condition_variable cv; 31 std::mutex mut; 32 33 int test1 = 0; 34 int test2 = 0; 35 36 bool expect_timeout = false; 37 f()38void f() 39 { 40 typedef std::chrono::system_clock Clock; 41 typedef std::chrono::milliseconds milliseconds; 42 std::unique_lock<std::mutex> lk(mut); 43 assert(test2 == 0); 44 test1 = 1; 45 cv.notify_one(); 46 Clock::time_point t0 = Clock::now(); 47 Clock::time_point wait_end = t0 + milliseconds(250); 48 Clock::duration d; 49 do { 50 d = wait_end - Clock::now(); 51 if (d <= milliseconds(0)) break; 52 } while (test2 == 0 && cv.wait_for(lk, d) == std::cv_status::no_timeout); 53 Clock::time_point t1 = Clock::now(); 54 if (!expect_timeout) 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 } 65 main(int,char **)66int main(int, char**) 67 { 68 { 69 std::unique_lock<std::mutex> lk(mut); 70 std::thread t = support::make_test_thread(f); 71 assert(test1 == 0); 72 while (test1 == 0) 73 cv.wait(lk); 74 assert(test1 != 0); 75 test2 = 1; 76 lk.unlock(); 77 cv.notify_one(); 78 t.join(); 79 } 80 test1 = 0; 81 test2 = 0; 82 expect_timeout = true; 83 { 84 std::unique_lock<std::mutex> lk(mut); 85 std::thread t = support::make_test_thread(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