xref: /llvm-project/libcxx/test/std/thread/thread.condition/thread.condition.condvar/notify_all.pass.cpp (revision 840e857a1969927f513a17e46445bf9a56cf81ba)
1 //===----------------------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // UNSUPPORTED: no-threads
10 
11 // <condition_variable>
12 
13 // class condition_variable;
14 
15 // void notify_all();
16 
17 #include <atomic>
18 #include <condition_variable>
19 #include <mutex>
20 #include <thread>
21 #include <cassert>
22 
23 #include "make_test_thread.h"
24 #include "test_macros.h"
25 
26 std::condition_variable cv;
27 std::mutex mut;
28 
29 int test0 = 0;
30 int test1 = 0;
31 int test2 = 0;
32 
33 std::atomic<int> ready_count(0);
34 
35 void f1()
36 {
37     std::unique_lock<std::mutex> lk(mut);
38     assert(test1 == 0);
39     ready_count += 1;
40     while (test1 == 0)
41         cv.wait(lk);
42     assert(test1 == 1);
43     test1 = 2;
44 }
45 
46 void f2()
47 {
48     std::unique_lock<std::mutex> lk(mut);
49     assert(test2 == 0);
50     ready_count += 1;
51     while (test2 == 0)
52         cv.wait(lk);
53     assert(test2 == 1);
54     test2 = 2;
55 }
56 
57 int main(int, char**)
58 {
59     std::thread t1 = support::make_test_thread(f1);
60     std::thread t2 = support::make_test_thread(f2);
61     while (ready_count.load() != 2) {
62       std::this_thread::sleep_for(std::chrono::milliseconds(100));
63     }
64     {
65         std::unique_lock<std::mutex>lk(mut);
66         test1 = 1;
67         test2 = 1;
68     }
69     cv.notify_all();
70     {
71         std::this_thread::sleep_for(std::chrono::milliseconds(100));
72         std::unique_lock<std::mutex>lk(mut);
73     }
74     t1.join();
75     t2.join();
76     assert(test1 == 2);
77     assert(test2 == 2);
78 
79   return 0;
80 }
81