1 //编写一个 程序,开启3个线程,这3个线程的ID分别为A,B,C 2 //每个线程将自己的ID在屏幕打印10遍 3 //要求输出结果必须按ABC的顺序显示 4 #include <iostream> 5 #include <thread> 6 #include <mutex> 7 #include <condition_variable> 8 using namespace std; 9 10 int LOOP = 10; 11 int flag = 0; 12 13 mutex m; 14 condition_variable cv; 15 16 void fun(int id) 17 { 18 for (int i = 0; i < LOOP; i++) 19 { 20 //设置锁定 21 unique_lock<mutex> ulk(m); 22 while(id != flag) 23 { 24 //不是该出现的场合则继续等待通知,然后再执行while判断 25 cv.wait(ulk); 26 } 27 //输出 28 char ch = 'A' + id; 29 cout << ch; 30 flag = (flag + 1) % 3; 31 //通知全部 32 cv.notify_all(); 33 } 34 } 35 36 void main() 37 { 38 thread t1(fun, 0); 39 thread t2(fun, 1); 40 thread t3(fun, 2); 41 t1.join(); 42 t2.join(); 43 t3.join(); 44 45 cin.get(); 46 }