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::getstd::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内的数据,而不是复制。
相关推荐
saltymilk8 小时前
C++ 模板参数推导问题小记(模板类的模板构造函数)
c++·模板元编程
感哥9 小时前
C++ lambda 匿名函数
c++
沐怡旸15 小时前
【底层机制】std::unique_ptr 解决的痛点?是什么?如何实现?怎么正确使用?
c++·面试
感哥15 小时前
C++ 内存管理
c++
博笙困了21 小时前
AcWing学习——双指针算法
c++·算法
感哥1 天前
C++ 指针和引用
c++
感哥1 天前
C++ 多态
c++
沐怡旸2 天前
【底层机制】std::string 解决的痛点?是什么?怎么实现的?怎么正确用?
c++·面试
River4162 天前
Javer 学 c++(十三):引用篇
c++·后端
感哥2 天前
C++ std::set
c++