1 //===----------------------------------------------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is dual licensed under the MIT and the University of Illinois Open 6 // Source Licenses. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // UNSUPPORTED: libcpp-has-no-threads 11 12 // <condition_variable> 13 14 // class condition_variable; 15 16 // template <class Rep, class Period, class Predicate> 17 // bool 18 // wait_for(unique_lock<mutex>& lock, 19 // const chrono::duration<Rep, Period>& rel_time, 20 // Predicate pred); 21 22 #include <condition_variable> 23 #include <mutex> 24 #include <thread> 25 #include <chrono> 26 #include <cassert> 27 28 class Pred 29 { 30 int& i_; 31 public: Pred(int & i)32 explicit Pred(int& i) : i_(i) {} 33 operator ()()34 bool operator()() {return i_ != 0;} 35 }; 36 37 std::condition_variable cv; 38 std::mutex mut; 39 40 int test1 = 0; 41 int test2 = 0; 42 43 int runs = 0; 44 f()45void f() 46 { 47 typedef std::chrono::system_clock Clock; 48 typedef std::chrono::milliseconds milliseconds; 49 std::unique_lock<std::mutex> lk(mut); 50 assert(test2 == 0); 51 test1 = 1; 52 cv.notify_one(); 53 Clock::time_point t0 = Clock::now(); 54 bool r = cv.wait_for(lk, milliseconds(250), Pred(test2)); 55 ((void)r); // Prevent unused warning 56 Clock::time_point t1 = Clock::now(); 57 if (runs == 0) 58 { 59 assert(t1 - t0 < milliseconds(250)); 60 assert(test2 != 0); 61 } 62 else 63 { 64 assert(t1 - t0 - milliseconds(250) < milliseconds(50)); 65 assert(test2 == 0); 66 } 67 ++runs; 68 } 69 main()70int main() 71 { 72 { 73 std::unique_lock<std::mutex>lk(mut); 74 std::thread t(f); 75 assert(test1 == 0); 76 while (test1 == 0) 77 cv.wait(lk); 78 assert(test1 != 0); 79 test2 = 1; 80 lk.unlock(); 81 cv.notify_one(); 82 t.join(); 83 } 84 test1 = 0; 85 test2 = 0; 86 { 87 std::unique_lock<std::mutex>lk(mut); 88 std::thread t(f); 89 assert(test1 == 0); 90 while (test1 == 0) 91 cv.wait(lk); 92 assert(test1 != 0); 93 lk.unlock(); 94 t.join(); 95 } 96 } 97