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内的数据,而不是复制。
相关推荐
「QT(C++)开发工程师」6 小时前
C++ 11 常用for循环
开发语言·c++
我还记得那天6 小时前
0 初识C++
开发语言·c++
FfHUCisI7 小时前
Go 编译过程全景
开发语言·后端·golang
FfHUCisI7 小时前
Golang 语法分析与 AST:Parser 与 go/ast
开发语言·后端·golang
lemon_sjdk8 小时前
ObjectProperty
java·开发语言·算法
大模型码小白8 小时前
Spring AI Tool 实现自然语言操作 MySQL 数据库详解
服务器·开发语言·数据库·人工智能·python·mysql·spring
hh9508 小时前
Agent Plan x DeepSeek Harness:Agent 供应链安全与第三方插件审计
java·开发语言·安全·agent plan·adg成都社区·adg社区
「QT(C++)开发工程师」8 小时前
C++ std::move 详解
开发语言·c++
matlab代码8 小时前
基于matlab的玉米种子计数设计(GUI界面)【源码58期】
开发语言·matlab