Home >Backend Development >C++ >What is the role of condition variables in C++ multi-threaded programming?
Condition variables are used for thread synchronization, allowing threads to wait for specific conditions to be met. Specific functions include: Notifying threads: Threads call notify_one() or notify_all() to notify other threads that the conditions have been met. Waiting condition: The thread calls wait() to wait for the condition to be met. After the condition is met, the thread is awakened.
The role of condition variables in C++ multi-threaded programming
Introduction
Conditions A variable is a synchronization primitive used for thread synchronization, allowing a thread to wait for a specific condition to be met. In C++, condition variables are implemented through the std::condition_variable
class.
Function
The function of condition variables is:
or
notify_all() function notifies other threads that a certain condition has been met.
function. When the condition is met, the thread will be awakened.
Practical Case
Consider the following producer-consumer problem using condition variables:#include <iostream> #include <condition_variable> #include <mutex> std::mutex m; // 互斥锁 std::condition_variable cv; // 条件变量 bool ready = false; // 是否准备好 void producer() { std::unique_lock<std::mutex> lock(m); // 生产数据... ready = true; cv.notify_one(); // 通知消费者数据已准备好 } void consumer() { std::unique_lock<std::mutex> lock(m); while (!ready) { cv.wait(lock); } // 等待数据准备好 // 消费数据... } int main() { std::thread t1(producer); std::thread t2(consumer); t1.join(); t2.join(); return 0; }In this example, the producer The thread uses condition variables to notify the consumer that thread data is ready. The consumer thread waits on the condition variable until the data is ready.
Conclusion
Condition variables are a powerful tool in C++ for synchronizing multi-threaded programs. They allow a thread to wait for a specific condition until that condition is met.The above is the detailed content of What is the role of condition variables in C++ multi-threaded programming?. For more information, please follow other related articles on the PHP Chinese website!