三スレッド順印刷ABC問題

1279 ワード

テーマ:プログラムを作成して、3つのスレッドを開いて、この3つのスレッドのIDはそれぞれA、B、Cで、各スレッドは自分のIDをスクリーンの上で10回印刷して、出力結果はABCの順序で表示しなければならないことを要求します;如:ABCABC....順番に押す.
#include 
#include 
#include 

using namespace std;

mutex m; //         
condition_variable cond; //    

int loop = 10;
int flag = 0;

void func(int id) {
    for(int i = 0; i < loop; i++) {
        unique_lock lk(m);//        
	while(flag !=id)
	    cond.wait(lk);//     ,  notify  
	cout << static_cast('A' + id) << " ";
	flag = (flag + 1) % 3;
	cond.notify_all();//    
    }
}

int main(int argc, char **argv) {
    cout << "Hello, world!" << std::endl;
    thread threadA(func, 0);
    thread threadB(func, 1);
    thread threadC(func, 2);
    
    cout << endl;
    
    threadA.join();
    threadB.join();
    threadC.join();
    return 0;
}

分析:
条件変数condition_variableは、マルチスレッド間の通信に使用され、1つまたは複数のスレッドを同時にブロックすることができる.condition_variableはunique_とロックを組み合わせて使用します.
condition_variableオブジェクトのwait関数が呼び出されるとunique_が使用されます.lock(mutexを介して)現在のスレッドを一時停止します.現在のスレッドは、別のスレッドが同じになるまでブロックされます:condition_variableオブジェクトでnotification関数が呼び出され、現在のスレッドが呼び出されます.