29.迅雷多线程面试题

 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 }

 

转载于:https://www.cnblogs.com/xiaochi/p/8549661.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值