C++11 并发(一道笔试题目)

时间:2023-03-09 21:16:01
C++11 并发(一道笔试题目)

题目:编写一个程序,开启3个线程,这3个线程的ID分别为A、B、C,每个线程将自己的ID在屏幕上打印10遍,要求输出结果必须按ABC的顺序显示;如:ABCABC….依次递推。

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable> using namespace std; mutex m;
condition_variable cond;
int LOOP=;
int flag=; void PrintID_A()
{
for(int i=;i<LOOP;i++)
{
unique_lock<mutex> locker(m); while(flag!=)
cond.wait(locker);
cout<<"A ";
flag=(flag+)%;
cond.notify_all();
}
} void PrintID_B()
{
for(int i=;i<LOOP;i++)
{
unique_lock<mutex> locker(m);
while(flag!=)
cond.wait(locker);
cout<<"B ";
flag=(flag+)%;
cond.notify_all();
}
} void PrintID_C()
{
for(int i=;i<LOOP;i++)
{
unique_lock<mutex> locker(m);
while(flag!=)
cond.wait(locker);
cout<<"C ";
flag=(flag+)%;
cond.notify_all();
}
} int main(){ thread A(PrintID_A);
thread B(PrintID_B);
thread C(PrintID_C); A.join();
B.join();
C.join();
cout<<endl; return ;
}