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