C++ 并发编程 | future与async

一、async

1、定义

2、启动策略

async函数接受两种不同的启动策略,这些策略在std::launch枚举中定义,如下:

  • std::launch::defered:这种策略意味着任务将在调用future::get()future::wait函数时延迟执行,也就是任务将在需要结果时同步执行
  • std::launch::async:任务在单独一个线程上异步执行

默认情况下async使用std::launch::defered | std::launch::async策略,这意味着任务可能异步执行,也可能延迟执行,具体取决于实现,示例:

#include <iostream>
#include <thread>
#include <future>
using namespace std;

thread::id  test_async() {
	this_thread::sleep_for(chrono::milliseconds(500));
	return this_thread::get_id();
}

thread::id  test_async_deferred() {
	this_thread::sleep_for(chrono::milliseconds(500));
	return this_thread::get_id();
}

int main() {
    // 另起一个线程去运行test_async
	future<thread::id> ans = std::async(launch::async, test_async);
	// 还没有运行test_async_deferred
	future<thread::id> ans_def = std::async(launch::deferred,test_async_deferred); //还没有运行test_async_deferred

	cout << "main thread id = " << this_thread::get_id() << endl;
	// 如果test_async这时还未运行完,程序会阻塞在这里,直到test_async运行结束返回
	cout << "test_async thread id = " << ans.get() << endl;
	// 这时候才去调用test_async_deferred,程序会阻塞在这里,直到test_async_deferred运行返回
	cout << "test_async_deferred thread id =  = " << ans_def.get() << endl;

	return 0;
}

输出结果

main thread id = 1
test_async thread id = 2
test_async_deferred thread id =  = 1

Process returned 0 (0x0)   execution time : 1.387 s
Press any key to continue.

从输出结果可以看出采用std::launch::defered策略时任务是同步执行,采用launch::async策略时任务是异步执行。

  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值