c++11 std::future获取异步线程函数的返回值

此博客展示了一段C++代码,利用std::future获取异步操作线程函数的返回值,通过std::async创建异步task。还介绍了获取future结果的三种方式,包括wait、get以及用wait_for查询状态,并对不同状态进行了输出处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1 #include<iostream>
  2 #include<future>
  3 #include<thread>
  4 #include<chrono>
  5 
  6 int func(int arv)
  7 {
  8     std::this_thread::sleep_for(std::chrono::seconds(5));    //睡眠5秒
  9     return arv &= 0xFF;
 10 }
 11 
 12 void testfuture()
 13 {
 14     //通过std::future获取异步操作线程函数的返回值, 这里用std::async创建异步的task
 15     std::future<int> fu = std::async(func, 3);
 16     
 17     //获取future结果有三种方式:
 18  
 19     //1. fu.wait();             //等待线程结束,无返回值
 20     //2. auto res = fu.get();   //等待线程结束并获取返回值
 21     
 22     //3. 用wait_for查询future的状态, future的状态有三种
 23     std::future_status status;
 24     do
 25     {
 26         status = fu.wait_for(std::shrono::seconds(1));  
 27         if(status == std::future_status::deferred)      //异步操作还没开始
 28             std::cout << "deferred" << std::endl;
 29         else if(status == std::future_status::timeout)  //异步操作超时
 30             std::cout << "timeout" << std::endl;
 31         else if(status == std::future_status::ready)    //异步操作已完成
 32             std::cout << "ready" << std::endl;
 33     
 34     }while(status != std::future_status::ready);
 35 }
 36 
 37 int main(int argc, char* argv[])
 38 {   
 39     testfuture();
 40     return 0;
 41 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值