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内的数据,而不是复制。
相关推荐
爱上语文4 分钟前
Springboot多种请求参数
java·开发语言·spring boot·spring
Smartdaili China4 分钟前
使用 Puppeteer-Cluster 和代理进行高效网络抓取: 完全指南
大数据·开发语言·网络·爬虫·php·puppeteer·代理服务器
朝闻dao5 分钟前
代码随想录八股训练营第四十天| C++
c++
Pandaconda7 分钟前
【计算机网络 - 基础问题】每日 3 题(十三)
开发语言·经验分享·笔记·后端·计算机网络·面试·职场和发展
梁辰兴34 分钟前
C语言 使用scanf函数时出现错误代码C4996
c语言·开发语言·scanf
m0_6837909540 分钟前
c++ 类中特殊成员函数
c++
chusheng18401 小时前
Python 中的 Socket 编程入门
开发语言·网络·python
ZHOUPUYU1 小时前
最新Kali Linux超详细安装教程(附镜像包)
linux·运维·服务器·开发语言·网络
讓丄帝愛伱1 小时前
SpringDataJpa自关联映射时出现StackOverflowError
java·开发语言
ihchenchen1 小时前
springboot国际化
java·开发语言