18.4 Condition Variables

18.4.1 Do not use std::condition_variable_any on a std::mutex

When using std::condition_variable_any, there is potential for additional costs in terms of size, performance or operating system resources, because it is more general than std::condition_variable. std::condition_variable works with std::unique_lock<std::mutex>, while std::condition_variable_any can operate on any objects that have lock and unlock member functions.

#include <mutex>
#include <condition_variable>
#include <vector>
#include <cstdint>
std::mutex mut;
std::condition_variable_any cv;
std::vector<int32_t> container;
void producerThread()
int32_t i = 0;
std::lock_guard<std::mutex> guard(mut);
// critical section
void consumerThread()
std::unique_lock<std::mutex> guard(mut);
// @@- Non-Compliant: conditional_variable_any used with std::mutex based lock 'guard' -@@
cv.wait(guard, []{ return !container.empty(); } );
// critical section


  • Williams Concurrency – 4.1.1

Click here for references