0

In the std::condition_variable example in cppreference.com, it manually unlocks the mutex before calling cv.notify_one():

    // 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();

From the notes on notify_one in cppreference.com: (emphasis mine)
(Not sure if I understood these notes correctly though. Maybe I should post another question on this.)

The notifying thread does not need to hold the lock on the same mutex as the one held by the waiting thread(s); in fact doing so is a pessimization, since the notified thread would immediately block again, waiting for the notifying thread to release the lock. However, some implementations (in particular many implementations of pthreads) recognize this situation and avoid this "hurry up and wait" scenario by transferring the waiting thread from the condition variable's queue directly to the queue of the mutex within the notify call, without waking it up.

Notifying while under the lock may nevertheless be necessary when precise scheduling of events is required, e.g. if the waiting thread would exit the program if the condition is satisfied, causing destruction of the notifying thread's condition variable. A spurious wakeup after mutex unlock but before notify would result in notify called on a destroyed object.

As far as I understand, this and this answers say it's better (at least not worse) to unlock before notifying. But @MaximEgorushkin and @DavidSchwartz's comments in this answer and DavidSchwartz's answer say that notifying before unlocking is better.

Does it depend on the situation or is it personal preference? When should I manually unlock the mutex before notifying?

starriet
  • 2,565
  • 22
  • 23
  • 1
    My understanding is that it's better to unlock then notify, as that reduces lock contention. The thread waiting on the condition variable is going to lock the mutex as soon as it wakes up, so it's better to have the mutex unlocked and ready. The choice doesn't affect correctness - a program that deadlocks or otherwise misbehaves in one case but not the other likely contains a race condition; a race-free program should work correctly either way. One answer arguing for notifying first says it improves fairness; this, I must admit, I don't know enough about. – Igor Tandetnik Jul 16 '23 at 16:26
  • For the case where it's better to notify first and then unlock, there's `notify_all_at_thread_exit` which has an [LWG issue](https://cplusplus.github.io/LWG/issue3343) demonstrating the case where the condition variable may be destroyed if the unlock comes first. – Hasturkun Jul 17 '23 at 13:06

0 Answers0