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_all();
     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_all();
     61     {
     62         std::this_thread::sleep_for(std::chrono::milliseconds(100));
     63         std::unique_lock<std::mutex>lk(mut);
     64     }
     65     t1.join();
     66     t2.join();
     67     assert(test1 == 2);
     68     assert(test2 == 2);
     69 }
     70