• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 // template <class Predicate>
17 //   void wait(unique_lock<mutex>& lock, Predicate pred);
18 
19 #include <condition_variable>
20 #include <mutex>
21 #include <thread>
22 #include <functional>
23 #include <cassert>
24 
25 std::condition_variable cv;
26 std::mutex mut;
27 
28 int test1 = 0;
29 int test2 = 0;
30 
31 class Pred
32 {
33     int& i_;
34 public:
Pred(int & i)35     explicit Pred(int& i) : i_(i) {}
36 
operator ()()37     bool operator()() {return i_ != 0;}
38 };
39 
f()40 void f()
41 {
42     std::unique_lock<std::mutex> lk(mut);
43     assert(test2 == 0);
44     test1 = 1;
45     cv.notify_one();
46     cv.wait(lk, Pred(test2));
47     assert(test2 != 0);
48 }
49 
main()50 int main()
51 {
52     std::unique_lock<std::mutex>lk(mut);
53     std::thread t(f);
54     assert(test1 == 0);
55     while (test1 == 0)
56         cv.wait(lk);
57     assert(test1 != 0);
58     test2 = 1;
59     lk.unlock();
60     cv.notify_one();
61     t.join();
62 }
63