C++ 并发编程中condition_variable和future的区别

std::condition_variable 和 std::future 的区别:

用途不同:

std::condition_variable:

就好比是一把魔法门,有两个小朋友,一个在门这边,一个在门那边。门上贴了一张纸,写着"开心时可以进来"。现在,门这边的小朋友要等着看门那边的小朋友什么时候准备好,准备好了就告诉门这边可以进来了。门这边的小朋友就用 std::condition_variable 等待门那边小朋友的通知,门那边小朋友准备好了就通知过来。

std::future:

这就像是委托一个任务给一个小助手。你告诉小助手:"嘿,你去超市买一瓶果汁,等你回来告诉我。"这里,你是主线程,小助手是异步线程,你用 std::future 去拿到小助手的结果,看他是否买到了果汁。

例子:

std::condition_variable:

cpp 复制代码
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>

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

void friend1() {
    std::this_thread::sleep_for(std::chrono::seconds(2));

    {
        std::lock_guard<std::mutex> lock(mtx);
        isReady = true;  // 小朋友在门那边准备好了
    }

    cv.notify_one();  // 通知门这边的小朋友
}

void friend2() {
    std::unique_lock<std::mutex> lock(mtx);
    cv.wait(lock, [] { return isReady; });  // 等待门那边的小朋友通知
    std::cout << "Friend 2: Let's go inside and play!" << std::endl;
}

int main() {
    std::thread t1(friend1);
    std::thread t2(friend2);

    t1.join();
    t2.join();

    return 0;
}

std::future:

cpp 复制代码
#include <iostream>
#include <future>

int buyJuice() {
    std::this_thread::sleep_for(std::chrono::seconds(2));
    return 1;  // 假设小助手成功买到果汁
}

int main() {
    std::future<int> result = std::async(buyJuice);

    std::cout << "Main thread: Waiting for the assistant to come back with juice..." << std::endl;

    int juice = result.get();  // 阻塞等待小助手的结果
    std::cout << "Main thread: Got the juice! It's a refreshing " << juice << std::endl;

    return 0;
}

为什么不能用条件变量替代期望?

如果我们用 std::condition_variable 代替 std::future,就像用等待通知的方式得知小助手是否买到果汁。这样你就必须一直等着,无法做其他事情。而 std::future 则允许你去做其他事情,等果汁买好了再回来拿。

总的来说,它们分别解决不同的问题,std::condition_variable 用于等待通知,而 std::future 用于异步任务的结果获取。

相关推荐
paeamecium3 分钟前
【PAT甲级真题】- Student List for Course (25)
数据结构·c++·算法·list·pat考试
Lyyaoo.29 分钟前
【JAVA基础面经】抽象类/方法与接口
java·开发语言
0xDevNull33 分钟前
Java实现Redis延迟队列:从原理到高可用架构
java·开发语言·后端
糖炒栗子032635 分钟前
Go 语言环境搭建与版本管理指南 (2026)
开发语言·后端·golang
于先生吖37 分钟前
无人共享健身房 Java 后端源码 + 多端对接完整方案
java·开发语言
cpp_learners1 小时前
银河麒麟V10+飞腾FT-2000/4处理器+QT源码静态编译5.14.2指南
开发语言·qt
野生技术架构师1 小时前
1000道互联网大厂Java岗面试原题解析(八股原理+场景题)
java·开发语言·面试
qqty12172 小时前
Java进阶学习之路
java·开发语言·学习
gCode Teacher 格码致知2 小时前
Javascript提高:get和post等请求,对于汉字和空格信息进行编码的原则-由Deepseek产生
开发语言·前端·javascript·node.js·jquery
黑眼圈子2 小时前
总结一下用Java做算法的常用类和方法
java·开发语言·算法