In C++, the condition variable is a synchronization primitive that is used to notify the other threads in a multithreading environment that the shared resource is free to access. It is defined as the std::condition_variable class inside the header file.
Condition variable is especially needed in cases where one thread has to wait for another thread execution to continue the work. For example, the producer-consumer relationship, sender-receiver relationship, etc.
In these cases, the condition variable makes the thread wait till it is notified by the other thread. It is used with mutex locks to block access to the shared resource when one thread is working on it.
The syntax to declare a condition variable is simple:
std::condition_variable variable_name;After that, we use the associated method for different operations.
The std::condition_variable methods contain some member methods to provide the basic functionalities. Some of these are: