Talk:cpp/thread/condition variable/notify one

The example code seems unnecessarily confusing - e.g.:

//Most probably, the waiting thread is awaken unnecessarily.

Why? Because 'i' has not been set yet so the wake up will appear spurious?

The same question with signals function taking mutex lock. Why does it do this? Because 'i' is being set? To check done?

It seems like using atomic and atomic would suffice and would help re-enforce the earlier statement that the lock doesn't need to be held - by showing no lock being held at all.

Am I totally missing the point?

Bubbafat (talk) 08:32, 18 November 2014 (PST)


 * I believe the example wants to demonstrate the effects of notifying a cv when the condition that is waited on is false and when it is true. A lock is needed in any case; you can't call cv.wait without a locked mutex. I'll try to reword the comments a bit. --Cubbi (talk) 08:37, 18 November 2014 (PST)


 * Thanks, the new wording makes it a bit clearer that the intent of the message was. I'm still not sure I understand why the signals function is taking the lock.  I agree that the wait function has to but the signals function is calli notify_one, not wait.  I'm probably missing the obvious. -- Bubbafat (talk) 09:50, 19 November 2014 (PST)


 * signals is using the lock to make "i = 1;" visible to the waiting thread, to pick up the new value of done from the signals thread and to, theoretically, avoid interleaved output on std::cout. Yes you could make i atomic, but that would no longer demonstrate the typical use of condition variables. --Cubbi (talk) 10:05, 19 November 2014 (PST)

pessimization Note
Is there any standar reference for the requirement of notify_one/notify_all working without acquiring the shared mutex first?

If the mutex is not acquired on MSVC the signal is ignored, there is also the following remark on https://msdn.microsoft.com/en-us/library/hh874761.aspx

''A calling thread must lock the mutex before it calls the functions that wait for the condition variable. The mutex is then locked when the called function returns.''

But I'm not sure about the meaning of calling thread and function that wait for the cv in this context.


 * the comment on MSDN refers to the thread that executes, , ("the functions that wait"), not the thread that is executing notify. The standard reference is thread.condition, though it isn't an easy read; Concurrency in Action is more approachable. --Cubbi (talk) 04:25, 4 March 2017 (PST)