C++ async future deferred

std::async 是一个接受可调用对象作为模板参数的函数模板,并有可能异步执行它们
std::async返回一个std::future,他存储由std::async()执行的可调用对象的返回值
并使用future的成员函数get()得到

不同的启动策略导致不一样的结果
当std::async使用的第一个参数是launch::async时,创建一个新的线程异步执行
当std::async使用的第一个参数是launch::deferred时,创建一个延时任务,直到get()函数调用时才会开始这个任务
默认参数是launch::async | launch::deferred它可以异步运行或不运行,这取决于系统的负载,即系统资源不够创建一个新线程时,那么就创建一个同步任务

#include<iostream>
#include<functional>
#include <thread>
#include <chrono>
using namespace std;
#include <mutex>
std::mutex mlock;
std::condition_variable cond;
 
#include <future>
int mythread() {
	std::cout << "my thread start,id = " << std::this_thread::get_id() << endl;
	this_thread::sleep_for(3s);
	std::cout << "my thread end,id = " << std::this_thread::get_id() << endl;
	return 5;
}
int main()
{
	//std::async 是一个接受可调用对象作为模板参数的函数模板,并有可能异步执行它们
	//std::async返回一个std::future<T>,他存储由std::async()执行的可调用对象的返回值
	//并使用future的成员函数get()得到
	std::cout << "main thread start,id = " << std::this_thread::get_id() << endl;

	std::future<int> result = std::async(mythread);
	//std::future<int> result = std::async(std::launch::async,mythread);
	//std::future<int> result = std::async(std::launch::deferred,mythread);
	this_thread::sleep_for(3s);
	int res = result.get();
	std::cout << "continue...." << std::endl;
	std::cout << res << std::endl;
	return 0;
}
//不同的启动策略导致不一样的结果
//当std::async使用的第一个参数是launch::async时,创建一个新的线程异步执行
//当std::async使用的第一个参数是launch::deferred时,创建一个延时任务,直到get()函数调用时才会开始这个任务
//默认参数是launch::async | launch::deferred它可以异步运行或不运行,这取决于系统的负载,即系统资源不够创建一个新线程时,那么就创建一个同步任务
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值