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