C++ 异步执行任务async()

前言

std::async是C++11新增的一个功能,它主要提供了一种方便的方式来执行异步任务。std::async函数模板会返回一个std::future对象,该对象表示异步任务的执行结果。

基本用法

函数原型

复制代码
std::future<T> async( std::launch policy, Function f, Args... args );
  • std::launch policy:这是一个可选参数,用于指定异步任务的启动策略。它可以是std::launch::async(尽可能异步执行),std::launch::deferred(延迟执行,直到调用std::future::get或std::future::wait),或者两者的按位或组合。如果不指定,则使用std::launch::async | std::launch::deferred。在具体开发使用中,不建议使用组合,因为行为可能会出现与开发目的不同的结果。
  • Function f:要异步执行的函数或可调用对象。可以是函数指针、函数对象和lambda函数
  • Args... args:传递给函数的参数,这里是一个参数包。

返回值

std::async返回值是一个std::future对象

std::future是一个模板类:

复制代码
tempalte<class T>
std::future<T>

数据类型T 取决于异步函数的返回值类型

使用示例

复制代码
#include <iostream> 
#include <future> 
#include <chrono> 
int compute(int x) 
{ 
	std::this_thread::sleep_for(std::chrono::seconds(1)); // 模拟耗时操作 
	return x * 2; 
} 

int main() 
{ 
	// 启动异步任务 
	auto future = std::async(std::launch::async, compute, 42); 

	// 获取异步操作的结果
	int result = future.get(); 
	// 阻塞直到异步操作完成,并获取结果 
	std::cout << "The result is " << result << std::endl; 
return 0; 
}

注意事项

  • std::async异常抛出:如果异步任务抛出异常,该异常会被储存在返回值std::future对象中,只有调用get()时,才会在本线程抛出。
  • 返回值std::future对象应该使用std::move来移动std::future内的数据,而不是复制。
相关推荐
Shaoshing5 分钟前
消息顺序
java·开发语言
音草13 分钟前
AVL 树详解:从概念到 C++ 实现
c++
云水初15 分钟前
【项目篇】基于LanGraph的自动处理客服邮件的 Agent汇总
开发语言·笔记·python·学习·fastapi·langgraph
茉莉玫瑰花茶16 分钟前
GO [ 内存与变量逃逸分析 ]
开发语言·后端·golang
凉茶钱23 分钟前
list:哨兵节点,const_iterator 和 const iterator的区别与迭代器失效
数据结构·c++·list
沫璃染墨33 分钟前
从零入门计算机网络系列(六):TCP套接字编程实战——从listen监听到客户端与服务器通信
linux·服务器·c++·tcp/ip·计算机网络·tcp
lhh_qrsly38 分钟前
OTA 加密完整方案(嵌入式 IoT 常用)
开发语言·物联网·php
Nontee1 小时前
Quartz 新手入门:定时任务的两个承诺
开发语言·windows·python
\光辉岁月/1 小时前
2.异常类
java·开发语言·异常类
淡海水1 小时前
05-03-源码-Boehm GC分配与碎片管理
开发语言·算法·unity·c#·游戏引擎·gc