C++ std::condition_variable使用方法

随笔2周前发布 刘尚泮
5 0 0

std::condition_variable 是 C++ 标准库中的一个类,用于在多线程环境中实现线程间的同步和通信。它通常与 std::mutex(互斥锁)一起使用,用于实现线程的等待和唤醒机制。

std::condition_variable 提供了以下主要成员函数:

wait(lock): 当前线程进入等待状态,直到另一个线程调用该 condition_variable 对象的 notify_one() 或 notify_all() 函数来唤醒等待的线程。lock 是一个 std::unique_lock 对象,用于在等待过程中自动释放关联的互斥锁。
notify_one(): 唤醒一个等待在该 condition_variable 对象上的线程。
notify_all(): 唤醒所有等待在该 condition_variable 对象上的线程。

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

std::mutex mtx;
std::condition_variable cv;
bool ready = false;

void workerThread()
{
    std::cout << "Worker thread is waiting..." << std::endl;
    std::unique_lock<std::mutex> lock(mtx);
    cv.wait(lock, [] { return ready; });
    std::cout << "Worker thread is awake!" << std::endl;
}

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

    // 主线程休眠一段时间
    std::this_thread::sleep_for(std::chrono::seconds(2));

    {
        std::lock_guard<std::mutex> lock(mtx);
        ready = true;
        // 唤醒等待中的线程
        cv.notify_one();
    }

    worker.join();

    return 0;
}

Worker thread is waiting...
Worker thread is awake!

在上述示例中,主线程创建了一个工作线程,并在工作线程中使用了 condition_variable 进行等待。主线程休眠2秒后,通过设置 ready 为 true,并调用 notify_one() 来唤醒工作线程。工作线程被唤醒后输出相应的消息。

需要注意的是,std::condition_variable 必须与 std::mutex 一起使用,以确保线程安全。

© 版权声明

相关文章

暂无评论

您必须登录才能参与评论!
立即登录
暂无评论...