温馨提示×

C++ notify在多线程编程中的应用

c++
小樊
82
2024-08-29 07:25:05
栏目: 编程语言

在C++多线程编程中,notify通常与条件变量(condition variables)一起使用,以实现线程间的同步和通信。条件变量允许一个或多个线程等待,直到另一个线程发出通知为止。这种机制可以用于解决生产者-消费者问题、读者-写者问题等常见的并发问题。

notify函数有两种形式:notify_onenotify_allnotify_one会唤醒一个正在等待的线程,而notify_all会唤醒所有正在等待的线程。

下面是一个简单的示例,展示了如何在C++中使用std::condition_variablenotify函数实现多线程同步:

#include<iostream>
#include<thread>
#include <mutex>
#include<condition_variable>

std::mutex mtx;
std::condition_variable cv;
int value = 0;

void worker_thread() {
    std::unique_lock<std::mutex> lock(mtx);
    cv.wait(lock, [] { return value != 0; }); // 等待条件满足
    std::cout << "Worker thread executed, value: "<< value<< std::endl;
}

int main() {
    std::thread worker(worker_thread);

    {
        std::lock_guard<std::mutex> lock(mtx);
        std::cout << "Main thread setting value to 10"<< std::endl;
        value = 10;
    }

    cv.notify_one(); // 通知等待的线程

    worker.join();
    return 0;
}

在这个示例中,我们创建了一个工作线程worker_thread,它会等待value变量的值不为0。主线程在设置value为10后,使用cv.notify_one()唤醒等待的工作线程。这样,工作线程可以继续执行,并输出value的值。

0