【C++ 多线程】轮流打印ABC多线程


轮流打印ABC多线程

代码实现:

 1 #include 
 2 #include 
 3 #include 
 4 #include 
 5 #include 
 6 #include 
 7 #include 
 8 #include 
 9 
10 std::mutex mtx;
11 std::condition_variable variable;
12 char g_ch = 0;
13 
14 void print_fun(char ch)
15 {
16     int cyle_cnt = 10;
17     char ch_ = ch - 'A';
18 
19     for (int i = 0; i < cyle_cnt; i++)
20     {
21         std::unique_lock ulk(mtx);
22         variable.wait(ulk, [ch_] { return ch_ == g_ch; });
23         std::cout << (char)(ch_ + 'A') << std::endl;
24         g_ch = (ch_ + 1) % 3;
25         ulk.unlock();
26 
27         variable.notify_all();
28     }
29 }
30 
31 int main()
32 {
33     std::vector threads;
34     threads.push_back(std::thread(print_fun, 'A'));
35     threads.push_back(std::thread(print_fun, 'B'));
36     threads.push_back(std::thread(print_fun, 'C'));
37 
38     std::for_each(threads.begin(), threads.end(), std::mem_fn(&std::thread::join));
39 
40     std::cout << std::endl;
41     return 0;
42 }

输出: