Home  >  Article  >  Backend Development  >  What is the role of condition variables in C++ multi-threaded programming?

What is the role of condition variables in C++ multi-threaded programming?

王林
王林Original
2024-06-04 09:31:01282browse

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.

C++ 多线程编程中 condition variables 的作用是什么?

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:

  • Notify the thread: A thread can call ## The #notify_one() or notify_all() function notifies other threads that a certain condition has been met.
  • Waiting conditions: Threads can wait for a certain condition to be satisfied by calling the wait() 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn