c++同時プログラミング:面接問題-スレッド同期


POSIXマルチスレッドプログラミング技術を熟知していますか?熟知している場合、作成プログラムは以下の機能を完成します.
1)int型グローバル変数g_があるFlagの初期値は0です.
2)スレッド1を主線称で起動し、「this is thread 1」を印刷し、g_Flagを1に設定
3)スレッド2を主線称で起動し、「this is thread 2」を印刷し、g_Flagを2に設定
4)ラインプログラム1はスレッド2が終了してから終了する必要がある
5)マスタスレッドがg_を検出しているFlagが1から2になったり、2から1になったりしたときに退出します
ここではC++11実装を採用し、std::future,std::promise実装の使い捨て同期については、次のリンクを参照してください.
#include  
#include  
#include  
#include  
#include  
#include  
#include  
#include  
#include
//#include  
using namespace std;
atomic flag(0);//        g_Flag     
mutex m;
condition_variable cond1;
condition_variable cond2;
condition_variable cond3;

void worker1(int f1){//  1  
	unique_locklk(m);
	
	printf("this is thread%d
",f1); flag = 1; cond3.notify_one(); while (flag != 2) cond1.wait(lk); printf("thread1 exit
"); cond3.notify_one(); } void worker2(int f2){// 1 unique_locklk(m); while (1 != flag) cond3.wait(lk); printf("this is thread%d
", f2); printf("thread2 exit
"); flag = 2; cond1.notify_all(); } int main(){ thread one(worker1, 1); thread two(worker2, 2); one.detach(); two.detach(); //pthread_exit(NULL);// unique_locklk(m); cond3.wait(lk); printf("main thread exit
"); return 0; }