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