Active vs. passive waiting (C++)

Active waiting

Don’t use this approach, because it will unnecessarily consume CPU time.

while (!m_flag) // std::atomic<bool>
{
  std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
// do stuff

The sleep reduces the CPU consumption, but increases the response time.

More:
– There is also std::this_thread::yield(), but it spins very often and consumes a lot of CPU.


Passive waiting

Use this approach, because it won’t unnecessarily consume CPU time.

std::unique_lock lock(cv_mutex_);
while (!m_flag) {
    m_condVar.wait(lock);
}
// do stuff

Alternative:

std::unique_lock lock(cv_mutex_);
cv_.wait(lock, [] { return m_flag; });
// do stuff

The mutex gets released as long as the cv is passively waiting for a notification.

More:
– It’s also possible that wait returns even if the cv has no notify yet, it’s called spurious wakeup.
– In the following post, you find an example: Singleton file logger with concurrent_queue (C++).