【发布时间】:2020-06-29 10:48:31
【问题描述】:
我使用以下代码测试std::condition_variable:
class CondWait{
public:
std::condition_variable cv;
std::mutex mu;
int i=0;
public:
void mainTask(){
std::unique_lock<std::mutex> lk(mu);
cv.wait(lk);
i++;
std::cout<<"main task, "<<i<<std::endl;
}
void notifyTask(){
std::unique_lock<std::mutex> lk(mu);
i = 0;
std::cout<<"notify task, "<<i<<std::endl;
cv.notify_one();
std::cout<<"notify task, sleep 5 sec"<<std::endl;
std::this_thread::sleep_for(std::chrono::seconds(5));
}
};
int main()
{
CondWait condwait;
std::thread t1(&CondWait::mainTask,&condwait);
std::thread t2(&CondWait::notifyTask,&condwait);
t1.join();
t2.join();
return 0;
}
有时,输出如下,程序被阻塞:
notify task, 0
notify task, sleep 5 sec
有时,程序会运行良好,即休眠5秒后,会输出main task, 1,完整输出为:
notify task, 0
notify task, sleep 5 sec
main task, 1
在我看来,在notifyTask线程中,在notify_one之后仍然使用互斥锁,所以mainTask中的wait无法锁定互斥锁。但是不知道接下来会发生什么,为什么这个例子会有歧义的表现。你能提供一些建议吗?非常感谢!
【问题讨论】:
标签: multithreading c++11 concurrency condition-variable