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内的数据,而不是复制。
相关推荐
eggwyw几秒前
C++深入浅出讲解希尔排序算法的实现
开发语言·c++
starzy19904 分钟前
Scala Array操作:从定长数组到ArrayBuffer的完整指南
开发语言·后端·scala
读书札记202216 分钟前
Qt UTF-8和UTF-8(BOM)
开发语言·qt
ShineWinsu19 分钟前
对于Qt:QProgressBar常见属性的解析
开发语言·c++·qt·进度条·gui·定时器·qprogressbar
fanruitian21 分钟前
python 机器学习 交叉验证train_test_split 网格搜索GridSearchCV
开发语言·python·机器学习
AlanAshley28 分钟前
无 SIM 卡也能打 110?手机紧急呼叫能力的软硬件技术探究
开发语言·智能手机·php
ShineWinsu30 分钟前
对于Qt:QLCDNumber常见属性以及QTimer的解析
服务器·数据库·c++·qt·gui·qtimer·qlcdnumber
modelmd33 分钟前
Go 切片、映射常见使用场景
开发语言·后端·golang
xiaoye-duck37 分钟前
《C++ 工具库实战》C++ 解析利器 JsonCpp:从基础使用到封装简易 JSON 工具
c++·json·第三方库
dialect_9 小时前
KMP算法
开发语言·c++·算法