C++11多线程异步操作std::future

本博客参考自https://thispointer.com/c11-tutorial/

C++多线程的在某些场景需要实现异步操作,由std::futer 和std::asych, std::packaged_task, std::promise搭配使用。

目录

1.std::future

2.std::promise

3.std::asych

4.std::packaged_task


1.std::future

std::future是一个类模板,它的模板类可访问“未来”的值,从而实现异步访问。

创建语法:

与std::futer 和std::asych, std::packaged_task, std::promise搭配使用对应的创建语法如下

std::future<int> futureObj = promiseObj.get_future();
std::future<std::string> resultFromDB = std::async(std::launch::async, fetchDataFromDB, "Data");
std::future<std::string> result = task.get_future();

调用语法:

获取future结果有三种方式:get、wait、wait_for,其中get等待异步操作结束并返回结果,wait只是等待异步操作完成,没有返回值,wait_for是超时等待返回结果(参考自https://blog.csdn.net/daaikuaichuan/article/details/81173303

std::cout<<futureObj.get()<<std::endl; //在get到值之前程序会一直等待

 

2.std::promise

创建语法:</

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值