C++ thread学习四(使用async创建线程并返回结果)

使用async创建一个新线程,返回一个future类型的对象,可以使用这种方法从线程中返回值。基本语法为:

std::future<线程函数返回值类型> res = std::async(标记, 线程入口函数);

标记常用的有std::launch::deferred和std::launch::async。

std::launch::async:意思是为当执行此行语句时线程被创建并开始执行,但是如果此线程没有被执行完,会被阻塞在res.get()或者res.wait(),直到执行完才被返回。

std::launch::deferred:不会创建新线程,当主线程执行到res.get()或者res.wait()之后会执行新线程里的内容并返回,效果类似与函数调用。

std::launch::async | std::launch::deferred:为系统默认缺省参数,含义为操作系统自行决定是否是async还是deferred(一般会创建新线程,但是如果系统资源紧张就会在当前线程执行)。

先看一个简单的例子:

#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include <future>

int mythread()
{
    sleep(3);
    std::cout << "another thread starts, thread id is " << std::this_thread::get_id() << '\n';
    std::cout << "another thread ends\n";
    return 10
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值