在notify_all()之后和wait()之前获取锁之间会发生什么? [英] what happen between after notify_all() and before wait() get the lock?
问题描述
我使用以下代码测试 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;
}
有时,输出在下面,程序被阻止:
Sometimes, the output is below and the program is blocked:
notify task, 0
notify task, sleep 5 sec
有时,该程序会运行良好,即睡眠5秒钟后,它将输出主要任务1
,完整的输出为:
Sometimes, the program will run well,i.e. after 5 seconds of sleep, it will output main task, 1
, the complete output is:
notify task, 0
notify task, sleep 5 sec
main task, 1
在我看来,在 notifyTask
线程中,互斥锁仍在 notify_one
之后使用,所以 mainTask中的
wait
无法锁定互斥锁.但是我不知道接下来会发生什么,为什么这个例子会有模糊的表现.您能提供一些建议吗?非常感谢!
In my opinion, int the notifyTask
thread, the mutex is still used after notify_one
, so the wait
in the mainTask
cannot lock the mutex. But I don't know what will happen next, why the example will have an ambiguity performance. Could you please provide some advice? Thanks a lot!
推荐答案
由于同时启动两个线程,可能会在 cv.wait()
在 mainTask
中,并且由于没有线程在等待,因此该功能没有任何作用.之后,执行 wait()
并挂起,等待通知
Since you start both threads concurrently perhaps a situation occurs when cv.notify_one()
is called before cv.wait()
in mainTask
and since no threads are waiting yet, the function does nothing. After that, wait()
is executed and hangs waiting for a notification
这篇关于在notify_all()之后和wait()之前获取锁之间会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!