简体   繁体   中英

Is it necessary to acquire the lock and notify condition_variable if no thread needs to wake up?

I was reading this reference and saw:

The thread that intends to modify the variable has to

  1. acquire a std::mutex (typically via std::lock_guard)

  2. perform the modification while the lock is held

  3. execute notify_one or notify_all on the std::condition_variable (the lock does not need to be held for notification)

If the change doesn't need to wake up threads, like on_pause function here, why is acquiring the lock (1) or calling notify (3) necessary? (Just waking them up to say good night?)

std::atomic<bool> pause_;
std::mutex pause_lock_;
std::condition_variable pause_event_;

void on_pause() // part of main thread
{
    // Why acquiring the lock is necessary?
    std::unique_lock<std::mutex> lock{ pause_lock_ };
    pause_ = true;
    // Why notify is necessary?
    pause_event_.notify_all();
}

void on_resume() // part of main thread
{
    std::unique_lock<std::mutex> lock{ pause_lock_ };
    pause = false;
    pause_event_.notify_all();
}

void check_pause() // worker threads call this
{
    std::unique_lock<std::mutex> lock{ pause_lock_ };
    pause_event_.wait(lock, [&](){ return !pause_; });
}

Your on_pause function sets pause_ to true, while the predicate in check_pause verifies that it is set to false. Hence calling notify_all in on_pause is pointless, because the notified threads in check_pause will check the predicate and immediately go back to sleep. And since pause_ is atomic and you don't need to call notify_all , you also don't need the lock.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM