编写程序完成如下功能:
1)有一int型全局变量g_Flag初始值为0
2) 在主线称中起动线程1,打印“this is thread1”,并将g_Flag设置为1
3) 在主线称中启动线程2,打印“this is thread2”,并将g_Flag设置为2
4) 线程序1需要在线程2退出后才能退出
5) 主线程在检测到g_Flag从1变为2,或者从2变为1的时候退出
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;
std::condition_variable cv;
std::mutex metx;
int g_Flag = 0;
int cnt = 0;
bool flag = false;
int main(void) {
thread t1([&]{
std::unique_lock<std::mutex> lk(metx);
cout << "this is thread1\n";
g_Flag = 1;
++cnt;
cv.wait(lk, [&]{{
return flag;
}});
cout << "thread1 exit\n";
});
thread t2([&]{
std::unique_lock<std::mutex> lk(metx);
cout << "this is thread2\n";
g_Flag = 2;
cnt++;
flag = true;
cv.notify_all();
cout << "thread2 exit\n";
});
t1.join();
t2.join();
std::unique_lock<std::mutex> lc(metx);
cv.wait(lc, [&]{
return cnt >= 2;
});
cout << "main thread exit\n";
return 0;
}
首先进入thread1,std::unique_lockstd::mutex lk(metx);给thread1上锁,输出"this is thread1\n",改g_Flag,++cnt。进入cv.wait(),条件为false,阻塞线程。同一个lk可以为一个线程上锁两次?还是等待条件为ture时调用metx.unlock()?
同时,一个全局变量metx可以给三个线程上锁吗?