I've seen a lot of implementations of the semaphore where the notify()
function looks something like this:
(this particular example is from here)
void notify() {
std::lock_guard<decltype(mutex_)> lock(mutex_);
++count_;
condition_.notify_one();
}
I don't understand the reason behind holding the lock while calling notify_one()
. Even if a spurious wake-up occurs after releasing the mutex but before notifying the condition variable, everything should work fine (since condition_.wait()
should use a predicate to handle spurious wakeups anyway).
Are there any cases where this:
void notify() {
{
std::scoped_lock lock(mutex_);
++count_;
}
condition_.notify_one();
}
would fail?