xref: /llvm-project/lldb/test/API/functionalities/thread/num_threads/main.cpp (revision 99451b4453688a94c6014cac233d371ab4cc342d)
1 #include "pseudo_barrier.h"
2 #include <condition_variable>
3 #include <mutex>
4 #include <thread>
5 #include <vector>
6 
7 std::mutex mutex;
8 std::condition_variable cond;
9 pseudo_barrier_t thread3_barrier;
10 
11 void *
thread3(void * input)12 thread3(void *input)
13 {
14     pseudo_barrier_wait(thread3_barrier);
15 
16     int dummy = 47; // thread3-before-lock
17 
18     std::unique_lock<std::mutex> lock(mutex);
19     cond.notify_all(); // Set thread3 break point on notify_all at this line.
20     return NULL;
21 }
22 
23 void *
thread2(void * input)24 thread2(void *input)
25 {
26     std::unique_lock<std::mutex> lock(mutex);
27     cond.notify_all(); // release main thread
28     cond.wait(lock);
29     return NULL;
30 }
31 
32 void *
thread1(void * input)33 thread1(void *input)
34 {
35     std::thread thread_2(thread2, nullptr);
36     thread_2.join();
37 
38     return NULL;
39 }
40 
main()41 int main()
42 {
43     std::unique_lock<std::mutex> lock(mutex);
44 
45     std::thread thread_1(thread1, nullptr);
46     cond.wait(lock); // wait for thread2
47 
48     pseudo_barrier_init(thread3_barrier, 10);
49 
50     std::vector<std::thread> thread_3s;
51     for (int i = 0; i < 10; i++) {
52       thread_3s.push_back(std::thread(thread3, nullptr));
53     }
54 
55     cond.wait(lock); // wait for thread_3s
56 
57     lock.unlock();
58 
59     thread_1.join();
60     for (auto &t : thread_3s){
61         t.join();
62     }
63 
64     return 0;
65 }
66