c++线程之 线程返回值、future、async

一、async、 future创建后台任务并返回值
希望返回一个结果
async是一个函数模板,用来启动一个异步任务,启动起来一个异步任务后,返回一个future对象

1、什么是异步任务: 就是自动创建一个线程并开始执行对应的线程的入口函数,它返回一个future对象
2、future对象里面就含有线程入口函数所返回的结果(线程返回结果,可以通过调用future对象的成员函数get()来获取)
#include <iostream>
#include <string>
#include <thread>
#include <vector>
#include <list>
#include <mutex>
#include <future>
using namespace std;

int mythread()
{
    cout << "子线程id = " << this_thread::get_id() << endl;
    //休息5秒钟
    chrono::milliseconds dura(5000);
    this_thread::sleep_for(dura);
    return 5;
}

int main()
{
    cout << "main" << "threadid =" << this_thread::get_id() << endl;
    future<int> result = async(mythread);
    cout << "continue... !" << endl;
    int def = 0;
    //得到线程返回值, 如果线程阻塞延时了呢? 那reult.get也会阻塞延时,等待线程返回值
    cout << result.get() << endl;
    cout << "I Love China!" << endl;
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值