Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manual unlocking done before notifying

Thanks to the book of the Doctor Scott Meyers, page 263, I recently discovered condition_variable, so I had to search about it on cppreference to study it more.

https://en.cppreference.com/w/cpp/thread/condition_variable

I have several questions on it, because I think on it since several days, and I still did not understand.

My questions are about this piece of code :

// Manual unlocking is done before notifying, to avoid waking up
// the waiting thread only to block again (see notify_one for details)
lk.unlock();
cv.notify_one();

1) I do not understand what the author of the cppreference means by that comment and by "the waiting thread, only to block again" because I don't know even how to translate it, and

2) Which threads it denotes exactly, and why in particular.

3) Does it denote the thread_worker or the main thread (parent) ?

4) What they chose to do that ?

And what does it change if the authors notify first and then manually unlock ?

like image 716
Dev Avatar asked Jul 11 '19 18:07

Dev


People also ask

How does Notify_one work?

notify_one : Signal a condition so that one of the thread waiting on this condition can resume. Thread A is supposed to finish whatever it is doing and then wake thread B to do its job. notify_one is the right choice here where one thread waits on the condition while the other thread can signal it.

What is the difference between Notify_one and Notify_all?

Show activity on this post. If there are ten threads blocked on the condition variable, for example, notify_one() will unblock only one thread, while notify_all() will unblock them all. In your case, you'll want to use notify_one() so you don't wake up threads that don't have any work waiting for them.

What is Condition_variable?

The condition_variable class is a synchronization primitive that can be used to block a thread, or multiple threads at the same time, until another thread both modifies a shared variable (the condition), and notifies the condition_variable . The thread that intends to modify the shared variable has to.

How does condition variable works C++?

A condition variable is an object able to block the calling thread until notified to resume. It uses a unique_lock (over a mutex ) to lock the thread when one of its wait functions is called.


1 Answers

That's a minor and usually irrelevant optimization. The concern arises because each thread that wakes up after a call to notify or notify_all has to lock the mutex before it is allowed to proceed. If the call to unlock occurs after the call to notify_one (or to notify), the thread(s) that wake up will have to wait until after the calling thread unlocks it. If the call to unlock is made before the notify call then one awakened thread can get the mutex immediately.

like image 149
Pete Becker Avatar answered Oct 21 '22 12:10

Pete Becker