1

It was already asked few times about whether one should notify condition_variable while holding a lock:

        lk.lock();
        // change state
        cv.notify_one();
        lk.unlock();

or after releasing it:

        lk.lock();
        // change state
        lk.unlock();
        cv.notify_one();

Here's one of such questions: Do I have to acquire lock before calling condition_variable.notify_one()?

Answers point out that both are safe, as long as the lock is held at all when condition is changed, and the later form is better for performance: awaken thread is immediately unlocked.

I'm wondering how much this performance effect is generic and significant:

  • Does this apply to Windows CONDITION_VARIABLE (that is avaliable since Vista+, but I'm nostly asking about Windows 10 implementation)? If so, how much significant the effect is?
  • Does this apply to Qt QWaitCondition on Windows?
  • Does this apply to boost::condition_variable on Windows?
  • Does it apply to most Linux systems where POSIX condition variable is the underlying implementation? Is there a measure of it?

The practical application is that I have to use the first form, where notification is done under the lock, as a structure that manages condition variables needs protection as well, so I want to know how much this approach worth avoiding.

Alex Guteniev
  • 12,039
  • 2
  • 34
  • 79
  • The answer will depend more on the implementation of the various mutexes than the condition variable. In scenario one you're effectively racing the notifying thread's call to `unlock` with the notified thread that is trying to acquire the mutex. – Botje Sep 04 '20 at 08:02
  • 2
    I'd write 2x3 test cases simulating some typical behavior in your codebase to measure the performance. I believe that'll give more value than theoretical answers here. – Ted Lyngmo Sep 04 '20 at 08:07
  • 1
    Just measure. It's gonna keep on being locking, so don't expect any big gains. Also, I think the key difference is not perf of "a single wakeup" but rather emergent behaviour - specifically _fair scheduling_. If you play it loose, the guarantees no thread will starve cannot be made. – sehe Sep 05 '20 at 11:15

0 Answers0