Search code examples
c++condition-variable

Are std::condition_variable wait predicates thread-safe?


Take this code:

std::condition_variable var;
var.wait(lock, [&sharedBool] { return sharedBool; });

When var reads from sharedBool, is that thread safe? If it isn't, is making sharedBool a std::atomic<bool> reasonable?


Solution

  • Reading from sharedBool happens under the protection of the mutex locked by lock.

    As long as all concurrent accessed to sharedBool happen while a lock to the same mutex is held, your program is thread-safe.

    Since you also cannot wait on a condition variable without holding a lock, it is usually not reasonable to use an atomic for this use case.