[知识点]c++ future库 async方法

2024-06-07 09:20

本文主要是介绍[知识点]c++ future库 async方法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

C++ 标准库中的 futureasync 提供了一种便捷的方式来实现并发编程。std::async 是一个非常强大的工具,它可以用于启动异步任务,并返回一个 std::future 对象,该对象可以用来等待任务的结果。

std::async 的基本用法

std::async 用于启动一个异步任务。它的基本语法如下:

#include <iostream>
#include <future>
#include <thread>// 一个简单的函数,模拟一些工作
int work(int x) {std::this_thread::sleep_for(std::chrono::seconds(2)); // 模拟延迟return x * x;
}int main() {// 使用 std::async 启动异步任务,并获取 std::future 对象std::future<int> result = std::async(std::launch::async, work, 10);// 在此处可以执行其他工作std::cout << "Doing other work..." << std::endl;// 获取异步任务的结果(会阻塞直到结果准备好)int value = result.get();std::cout << "Result: " << value << std::endl;return 0;
}

std::async 启动模式

std::async 提供了两种启动模式:

  1. std::launch::async:任务在独立线程中异步执行。
  2. std::launch::deferred:任务延迟执行,直到 future 对象的 getwait 方法被调用。
示例:不同的启动模式
#include <iostream>
#include <future>
#include <thread>int work(int x) {std::this_thread::sleep_for(std::chrono::seconds(2));return x * x;
}int main() {// 异步启动std::future<int> async_result = std::async(std::launch::async, work, 10);// 延迟启动std::future<int> deferred_result = std::async(std::launch::deferred, work, 20);// 在此处可以执行其他工作std::cout << "Doing other work..." << std::endl;// 获取异步任务的结果(会阻塞直到结果准备好)int async_value = async_result.get();std::cout << "Async result: " << async_value << std::endl;// 获取延迟任务的结果(会在此时执行任务)int deferred_value = deferred_result.get();std::cout << "Deferred result: " << deferred_value << std::endl;return 0;
}

使用 std::future 获取结果

std::future 提供了多种方法来获取任务结果:

  • get:阻塞当前线程,直到任务完成并返回结果。
  • wait:阻塞当前线程,直到任务完成。
  • wait_for:阻塞当前线程一段时间,等待任务完成。
  • wait_until:阻塞当前线程直到指定时间,等待任务完成。
示例:使用 std::future 的不同方法
#include <iostream>
#include <future>
#include <thread>int work(int x) {std::this_thread::sleep_for(std::chrono::seconds(2));return x * x;
}int main() {std::future<int> result = std::async(std::launch::async, work, 10);// 等待一段时间if (result.wait_for(std::chrono::seconds(1)) == std::future_status::timeout) {std::cout << "Task is still running..." << std::endl;}// 再次等待,直到任务完成result.wait();int value = result.get();std::cout << "Result: " << value << std::endl;return 0;
}

捕获异常

如果异步任务在执行过程中抛出异常,std::futureget 方法会重新抛出该异常。可以通过捕获异常来处理任务中的错误。

示例:捕获异常
#include <iostream>
#include <future>
#include <stdexcept>
#include <thread>int work(int x) {if (x < 0) {throw std::invalid_argument("x must be non-negative");}std::this_thread::sleep_for(std::chrono::seconds(2));return x * x;
}int main() {// 启动一个会抛出异常的任务std::future<int> result = std::async(std::launch::async, work, -10);try {int value = result.get(); // 这里会重新抛出异常std::cout << "Result: " << value << std::endl;} catch (const std::exception& e) {std::cout << "Exception: " << e.what() << std::endl;}return 0;
}

总结

  • std::async:用于启动异步任务,可以指定启动模式(asyncdeferred)。
  • std::future:用于获取异步任务的结果,提供多种方法(get, wait, wait_for, wait_until)。
  • 异常处理:通过 std::futureget 方法可以捕获异步任务中抛出的异常。

这篇关于[知识点]c++ future库 async方法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1038775

相关文章

C++11范围for初始化列表auto decltype详解

《C++11范围for初始化列表autodecltype详解》C++11引入auto类型推导、decltype类型推断、统一列表初始化、范围for循环及智能指针,提升代码简洁性、类型安全与资源管理效... 目录C++11新特性1. 自动类型推导auto1.1 基本语法2. decltype3. 列表初始化3

C++11右值引用与Lambda表达式的使用

《C++11右值引用与Lambda表达式的使用》C++11引入右值引用,实现移动语义提升性能,支持资源转移与完美转发;同时引入Lambda表达式,简化匿名函数定义,通过捕获列表和参数列表灵活处理变量... 目录C++11新特性右值引用和移动语义左值 / 右值常见的左值和右值移动语义移动构造函数移动复制运算符

Linux系统中查询JDK安装目录的几种常用方法

《Linux系统中查询JDK安装目录的几种常用方法》:本文主要介绍Linux系统中查询JDK安装目录的几种常用方法,方法分别是通过update-alternatives、Java命令、环境变量及目... 目录方法 1:通过update-alternatives查询(推荐)方法 2:检查所有已安装的 JDK方

SQL Server安装时候没有中文选项的解决方法

《SQLServer安装时候没有中文选项的解决方法》用户安装SQLServer时界面全英文,无中文选项,通过修改安装设置中的国家或地区为中文中国,重启安装程序后界面恢复中文,解决了问题,对SQLSe... 你是不是在安装SQL Server时候发现安装界面和别人不同,并且无论如何都没有中文选项?这个问题也

Java Thread中join方法使用举例详解

《JavaThread中join方法使用举例详解》JavaThread中join()方法主要是让调用改方法的thread完成run方法里面的东西后,在执行join()方法后面的代码,这篇文章主要介绍... 目录前言1.join()方法的定义和作用2.join()方法的三个重载版本3.join()方法的工作原

C++中detach的作用、使用场景及注意事项

《C++中detach的作用、使用场景及注意事项》关于C++中的detach,它主要涉及多线程编程中的线程管理,理解detach的作用、使用场景以及注意事项,对于写出高效、安全的多线程程序至关重要,下... 目录一、什么是join()?它的作用是什么?类比一下:二、join()的作用总结三、join()怎么

在MySQL中实现冷热数据分离的方法及使用场景底层原理解析

《在MySQL中实现冷热数据分离的方法及使用场景底层原理解析》MySQL冷热数据分离通过分表/分区策略、数据归档和索引优化,将频繁访问的热数据与冷数据分开存储,提升查询效率并降低存储成本,适用于高并发... 目录实现冷热数据分离1. 分表策略2. 使用分区表3. 数据归档与迁移在mysql中实现冷热数据分

Spring Boot从main方法到内嵌Tomcat的全过程(自动化流程)

《SpringBoot从main方法到内嵌Tomcat的全过程(自动化流程)》SpringBoot启动始于main方法,创建SpringApplication实例,初始化上下文,准备环境,刷新容器并... 目录1. 入口:main方法2. SpringApplication初始化2.1 构造阶段3. 运行阶

Olingo分析和实践之ODataImpl详细分析(重要方法详解)

《Olingo分析和实践之ODataImpl详细分析(重要方法详解)》ODataImpl.java是ApacheOlingoOData框架的核心工厂类,负责创建序列化器、反序列化器和处理器等组件,... 目录概述主要职责类结构与继承关系核心功能分析1. 序列化器管理2. 反序列化器管理3. 处理器管理重要方

Python错误AttributeError: 'NoneType' object has no attribute问题的彻底解决方法

《Python错误AttributeError:NoneTypeobjecthasnoattribute问题的彻底解决方法》在Python项目开发和调试过程中,经常会碰到这样一个异常信息... 目录问题背景与概述错误解读:AttributeError: 'NoneType' object has no at