// promise example
#include <iostream> // std::cout
#include <functional> // std::ref
#include <thread> // std::thread
#include <future> // std::promise, std::future
bool ok=false;
void print_int (std::future<int>& fut)
{
int x = fut.get(); //获取承诺的结果,可能等待
if (x==10000){
std::cout << "我已经收到承诺的" << x << "元" << '\n';
ok=true;
}
}
int main ()
{
std::promise<int> prom; //承诺:将来向账户打入10000元,但是现在暂时没钱。
std::future<int> fut = prom.get_future(); //我们向fut做出的承诺
std::thread trd (print_int, std::ref(fut)); //另一个线程启动
prom.set_value(10000); //兑现承诺:往账户里打入10000元
while(!ok);
std::cout << "你收到钱了? 我还是比较守信的吧" << '\n';
trd.join();
return 0;
}
学习笔记:future库的日常比喻
最新推荐文章于 2025-08-17 02:02:50 发布
本文通过实例探讨了C++并发编程中承诺(Promise)的概念及其在异步操作中的应用,展示了如何使用future来获取承诺的结果,并通过线程进行并发处理。
872

被折叠的 条评论
为什么被折叠?



