![](/img/trans.png)
[英]Calling std::condition_variable::notify_one() multiple times before std::condition_variable::wait() is called
[英]std::condition_variable::notify_one() called several times without context switching
在此示例中,將喚醒多少個等待線程:
第一線程 :
void wakeUp2Threads()
{
std::unique_lock<std::mutex> lock(condvar_mutex);
condvar.notify_one();
condvar.notify_one();
}
第二線程 :
{
std::unique_lock<std::mutex> lock(condvar_mutex);
condvar.wait(lock); <- 2nd thread has entered here before 1st thread entered wakeUp2Threads.
}
第三線程 (與第二線程相同):
{
std::unique_lock<std::mutex> lock(condvar_mutex);
condvar.wait(lock); <- 3rd thread has entered here before 1st thread entered wakeUp2Threads.
}
是否可以保證在此示例中,兩個通知都將傳遞到不同的線程,而不是多次傳遞到同一線程?
即notify_one()是什么意思:
1) notify one thread, no matter has it been already notified (but has not been woken up yet), or not. (* see note)
or
2) notify one thread, but only this one, which has not been notified yet.
(*) 請注意! 我不是在這里談論“等待線程已經在過去的某個地方被通知,喚醒,做一些事情並再次輸入condvar.wait()”的情況-當然,在這種情況下,幾個notify_one()例程可以喚醒相同的線程一遍又一遍。
我說的是另一種情況 :
notify_one()已通知等待線程有關喚醒的信息,但是在此等待線程從內核調度程序接收到時隙並繼續執行之前,已再次調用了另一個notify_one()。 盡管第二條通知尚未從第一條通知中喚醒,是否有可能再次將其傳遞到同一線程?
notify_one
調用從notify_one
解除了對一個線程的notify_one
。 這意味着,當第二次調用它時,它將無法解除阻塞,因為它不再被阻塞。
在標准30.5 / 3和30.5.1 / 7中對此進行了規定。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.