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 // <condition_variable>
     11 
     12 // class condition_variable;
     13 
     14 // template <class Rep, class Period>
     15 //     cv_status
     16 //     wait_for(unique_lock<mutex>& lock,
     17 //              const chrono::duration<Rep, Period>& rel_time);
     18 
     19 #include <condition_variable>
     20 #include <mutex>
     21 #include <thread>
     22 #include <chrono>
     23 #include <cassert>
     24 
     25 std::condition_variable cv;
     26 std::mutex mut;
     27 
     28 int test1 = 0;
     29 int test2 = 0;
     30 
     31 int runs = 0;
     32 
     33 void f()
     34 {
     35     typedef std::chrono::system_clock Clock;
     36     typedef std::chrono::milliseconds milliseconds;
     37     std::unique_lock<std::mutex> lk(mut);
     38     assert(test2 == 0);
     39     test1 = 1;
     40     cv.notify_one();
     41     Clock::time_point t0 = Clock::now();
     42     while (test2 == 0 &&
     43            cv.wait_for(lk, milliseconds(250)) == std::cv_status::no_timeout)
     44         ;
     45     Clock::time_point t1 = Clock::now();
     46     if (runs == 0)
     47     {
     48         assert(t1 - t0 < milliseconds(250));
     49         assert(test2 != 0);
     50     }
     51     else
     52     {
     53         assert(t1 - t0 - milliseconds(250) < milliseconds(50));
     54         assert(test2 == 0);
     55     }
     56     ++runs;
     57 }
     58 
     59 int main()
     60 {
     61     {
     62         std::unique_lock<std::mutex>lk(mut);
     63         std::thread t(f);
     64         assert(test1 == 0);
     65         while (test1 == 0)
     66             cv.wait(lk);
     67         assert(test1 != 0);
     68         test2 = 1;
     69         lk.unlock();
     70         cv.notify_one();
     71         t.join();
     72     }
     73     test1 = 0;
     74     test2 = 0;
     75     {
     76         std::unique_lock<std::mutex>lk(mut);
     77         std::thread t(f);
     78         assert(test1 == 0);
     79         while (test1 == 0)
     80             cv.wait(lk);
     81         assert(test1 != 0);
     82         lk.unlock();
     83         t.join();
     84     }
     85 }
     86