The std::condition_variable::wait
function requires a locked mutex as an argument. Example:
void ThreadPool::Worker() noexcept
{
while (true) {
std::function<void()> task;
{
std::unique_lock lock(mutex_); // ACQUIRE
cv_.wait(lock, [this] { return stop_ || !tasks_.empty(); }); // (RELEASE + SLEEP) - Atomically
// Do something (with a shared resource that is protected by the mutex)
}
// Do something else
}
}
In this specific scenario (which is quite common), acquiring and releasing the mutex_ seems redundant since there’s no other code execution between them. It appears to contradict the Zero-overhead principle: “In general, this means that no feature should be added to C++ that would impose any overhead, whether in time or space, greater than a programmer would introduce without using the feature.”
Is there maybe a race-condition when more than one thread calls wait simultaneously?
Otherwise, what sense in that?