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 // ALLOW_RETRIES: 2 11 12 // TODO(ldionne): This test fails on Ubuntu Focal on our CI nodes (and only there), in 32 bit mode. 13 // UNSUPPORTED: linux && 32bits-on-64bits 14 15 // <condition_variable> 16 17 // class condition_variable; 18 19 // template <class Clock, class Duration, class Predicate> 20 // bool 21 // wait_until(unique_lock<mutex>& lock, 22 // const chrono::time_point<Clock, Duration>& abs_time, 23 // Predicate pred); 24 25 #include <condition_variable> 26 #include <mutex> 27 #include <thread> 28 #include <chrono> 29 #include <cassert> 30 31 #include "make_test_thread.h" 32 #include "test_macros.h" 33 34 struct Clock 35 { 36 typedef std::chrono::milliseconds duration; 37 typedef duration::rep rep; 38 typedef duration::period period; 39 typedef std::chrono::time_point<Clock> time_point; 40 static const bool is_steady = true; 41 42 static time_point now() 43 { 44 using namespace std::chrono; 45 return time_point(duration_cast<duration>( 46 steady_clock::now().time_since_epoch() 47 )); 48 } 49 }; 50 51 class Pred 52 { 53 int& i_; 54 public: 55 explicit Pred(int& i) : i_(i) {} 56 57 bool operator()() {return i_ != 0;} 58 }; 59 60 std::condition_variable cv; 61 std::mutex mut; 62 63 int test1 = 0; 64 int test2 = 0; 65 66 int runs = 0; 67 68 void f() 69 { 70 std::unique_lock<std::mutex> lk(mut); 71 assert(test2 == 0); 72 test1 = 1; 73 cv.notify_one(); 74 Clock::time_point t0 = Clock::now(); 75 Clock::time_point t = t0 + Clock::duration(250); 76 bool r = cv.wait_until(lk, t, Pred(test2)); 77 Clock::time_point t1 = Clock::now(); 78 if (runs == 0) 79 { 80 assert(t1 - t0 < Clock::duration(250)); 81 assert(test2 != 0); 82 assert(r); 83 } 84 else 85 { 86 assert(t1 - t0 - Clock::duration(250) < Clock::duration(50)); 87 assert(test2 == 0); 88 assert(!r); 89 } 90 ++runs; 91 } 92 93 int main(int, char**) 94 { 95 { 96 std::unique_lock<std::mutex> lk(mut); 97 std::thread t = support::make_test_thread(f); 98 assert(test1 == 0); 99 while (test1 == 0) 100 cv.wait(lk); 101 assert(test1 != 0); 102 test2 = 1; 103 lk.unlock(); 104 cv.notify_one(); 105 t.join(); 106 } 107 test1 = 0; 108 test2 = 0; 109 { 110 std::unique_lock<std::mutex> lk(mut); 111 std::thread t = support::make_test_thread(f); 112 assert(test1 == 0); 113 while (test1 == 0) 114 cv.wait(lk); 115 assert(test1 != 0); 116 lk.unlock(); 117 t.join(); 118 } 119 120 return 0; 121 } 122