Active vs. passive waiting (C++)

Active waiting
Don’t use this approach, cause 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.


Passive waiting
Use this approach, cause it won’t unnecessarily consume CPU time.

std::unique_lock<std::mutex> lock(m_mutex);
m_condVar.wait(lock); // std::condition_variable
// do stuff

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

In this post you find an example.