问题
How many waiting threads will wake up in this example:
1st thread:
void wakeUp2Threads()
{
std::unique_lock<std::mutex> lock(condvar_mutex);
condvar.notify_one();
condvar.notify_one();
}
2nd thread:
{
std::unique_lock<std::mutex> lock(condvar_mutex);
condvar.wait(lock); <- 2nd thread has entered here before 1st thread entered wakeUp2Threads.
}
3rd thread (the same as 2nd):
{
std::unique_lock<std::mutex> lock(condvar_mutex);
condvar.wait(lock); <- 3rd thread has entered here before 1st thread entered wakeUp2Threads.
}
Is there any guarantee that in this example both notifications will be delivered to different threads, not the same thread several times?
I.e what does notify_one() mean:
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.
(*) Pay attention! I'm not talking here about scenario "waiting thread had already been notified somewhere in the past, woken up, done some stuff and entered condvar.wait() again" - of course, in this case several notify_one() routines can wake up the same thread over and over again.
I'm talking about another case:
notify_one() has notified waiting thread about wake-up, but BEFORE this waiting thread has received time slot form the kernel scheduler and continued execution - another notify_one() has been called again. Is it possible this second notification will be delivered to the same thread again, while it hasn't been woken up from first notification yet?
回答1:
The notify_one
call atomically unblocks one thread. That means that when called a second time it can't unblock the same thread as it's no longer blocked.
This is specified in the standard at section 30.5/3 and 30.5.1/7.
来源:https://stackoverflow.com/questions/15085823/stdcondition-variablenotify-one-called-several-times-without-context-switc