信号量实现-在通知condition_variable之前,notify()应该释放互斥量吗?

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).

是否有以下情况:

void notify() {
        {
        std::scoped_lock lock(mutex_);
        ++count_;
        }
        condition_.notify_one();
    }

会失败吗?

评论
  • 记得忘记
    记得忘记 回复

    According to cppreference (emphasis mine):

    打算修改变量的线程必须         获取std :: mutex(通常通过std :: lock_guard)   按住锁执行修改   在std :: condition_variable上执行notify_one或notify_all(不需要为通知而持有该锁)

    因此,您帖子中的任何代码序列都应该可以。