题目:编写一个程序,开启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=10;
int flag=1;

void PrintID_A()
{
    for(int i=0;i<LOOP;i++)
    {
        unique_lock<mutex> locker(m);

        while(flag!=1)
            cond.wait(locker);
        cout<<"A  ";
        flag=(flag+1)%3;
        cond.notify_all();
    }
}

void PrintID_B()
{
    for(int i=0;i<LOOP;i++)
    {
        unique_lock<mutex> locker(m);
        while(flag!=2)
            cond.wait(locker);
        cout<<"B  ";
        flag=(flag+1)%3;
        cond.notify_all();
    }
}

void PrintID_C()
{
    for(int i=0;i<LOOP;i++)
    {
        unique_lock<mutex> locker(m);
        while(flag!=0)
            cond.wait(locker);
        cout<<"C  ";
        flag=(flag+1)%3;
        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 0;
}

 

相关文章:

  • 2021-07-21
  • 2021-05-07
  • 2022-12-23
  • 2021-05-24
  • 2021-05-17
猜你喜欢
  • 2022-12-23
  • 2021-11-18
  • 2021-11-20
  • 2021-08-29
  • 2022-01-17
  • 2021-05-13
相关资源
相似解决方案