Описание тега condition-variable
In a multithreaded program it often happens that a thread cannot proceed until some condition is met, such as another thread completing a task, or providing some input to be processed. Instead of wasting CPU cycles by constantly checking, a condition variable can be used to make the thread go to sleep until the condition is met.
Using a condition variable requires three things: the condition variable itself, a lock (e.g. a mutex or critical section) that prevents other threads from modifying the data being used, and a predicate to test the condition being waited for (e.g to answer "has the other thread finished?" or "is there input to be processed?")
When calling a condition variable's "wait" function it will atomically release the lock and block the calling thread (it must be atomic so that there is no window where the condition could become true and the thread would miss the notification and sleep forever.) The thread will be unblocked when another thread notifies that the condition is true, at which point the condition variable reacquires the lock and the caller should test the predicate to check the condition.
Examples of condition variable types provided by different APIs:
- C++11:
std::condition_variable
andstd::condition_variable_any
- Boost:
boost::condition_variable
andboost::condition_variable_any
- POSIX:
pthread_cond_t
- Win32: (since Vista)
CONDITION_VARIABLE