zoukankan      html  css  js  c++  java
  • 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=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;
    }
  • 相关阅读:
    【leetcode】下一个排列
    【leetcode】配对交换
    【leetcode】两个相同字符之间的最长子字符串
    052-126&127
    052-125
    052-124
    052-123
    052-122
    052-121
    052-120
  • 原文地址:https://www.cnblogs.com/wxquare/p/4769693.html
Copyright © 2011-2022 走看看