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