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 // void notify_one(); 17 18 #include <condition_variable> 19 #include <atomic> 20 #include <mutex> 21 #include <thread> 22 #include <cassert> 23 24 25 std::condition_variable cv; 26 std::mutex mut; 27 28 std::atomic_int test1(0); 29 std::atomic_int test2(0); 30 f1()31void f1() 32 { 33 std::unique_lock<std::mutex> lk(mut); 34 assert(test1 == 0); 35 while (test1 == 0) 36 cv.wait(lk); 37 assert(test1 == 1); 38 test1 = 2; 39 } 40 f2()41void f2() 42 { 43 std::unique_lock<std::mutex> lk(mut); 44 assert(test2 == 0); 45 while (test2 == 0) 46 cv.wait(lk); 47 assert(test2 == 1); 48 test2 = 2; 49 } 50 main()51int main() 52 { 53 std::thread t1(f1); 54 std::thread t2(f2); 55 std::this_thread::sleep_for(std::chrono::milliseconds(100)); 56 { 57 std::unique_lock<std::mutex>lk(mut); 58 test1 = 1; 59 test2 = 1; 60 } 61 cv.notify_one(); 62 { 63 std::this_thread::sleep_for(std::chrono::milliseconds(100)); 64 std::unique_lock<std::mutex>lk(mut); 65 } 66 if (test1 == 2) 67 { 68 assert(test2 == 1); 69 t1.join(); 70 test1 = 0; 71 } 72 else if (test2 == 2) 73 { 74 assert(test1 == 1); 75 t2.join(); 76 test2 = 0; 77 } 78 else 79 assert(false); 80 cv.notify_one(); 81 { 82 std::this_thread::sleep_for(std::chrono::milliseconds(100)); 83 std::unique_lock<std::mutex>lk(mut); 84 } 85 if (test1 == 2) 86 { 87 assert(test2 == 0); 88 t1.join(); 89 test1 = 0; 90 } 91 else if (test2 == 2) 92 { 93 assert(test1 == 0); 94 t2.join(); 95 test2 = 0; 96 } 97 else 98 assert(false); 99 } 100