Junior — Middle
Explain the purpose and operation of std::condition_variable in C++.
sobes.tech AI
Answer from AI
std::condition_variable in C++ is used to organize synchronization between threads. It allows one or more threads to wait for a certain event to occur, while releasing the mutex so that other threads can modify the state that the first thread is waiting for.
Main points:
- A thread calls
waiton the condition_variable, passing the mutex it holds. - During waiting, the mutex is released, allowing other threads to access shared data.
- When the event occurs, another thread calls
notify_oneornotify_allto wake up the waiting threads. - After waking up, the thread re-acquires the mutex and checks the condition.
Example usage:
#include <mutex>
#include <condition_variable>
#include <queue>
std::mutex mtx;
std::condition_variable cv;
std::queue<int> dataQueue;
void producer() {
std::unique_lock<std::mutex> lock(mtx);
dataQueue.push(42);
cv.notify_one();
}
void consumer() {
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, []{ return !dataQueue.empty(); });
int data = dataQueue.front();
dataQueue.pop();
// process data
}
Thus, condition_variable helps efficiently organize waiting and notification between threads without active polling.