C++中如何使用std::async实现异步编程

来源:AI编程作者:梦乃头衔:网络博主
导读:本期聚焦于小伙伴创作的《C++中如何使用std::async实现异步编程》,敬请观看详情,探索知识的价值。以下视频、文章将为您系统阐述其核心内容与价值。如果您觉得《C++中如何使用std::async实现异步编程》有用,将其分享出去将是对创作者最好的鼓励。

在C++11标准之前,实现异步编程往往需要手动创建线程、管理线程生命周期,还要处理线程间的同步问题,流程比较繁琐。std::async的出现简化了这一流程,它可以直接启动一个异步任务,并且返回一个std::future对象,用于后续获取任务的执行结果。

C++中如何使用std::async实现异步编程

std::async的基本用法

std::async定义在<future>头文件中,它的基本调用形式有两种,一种是只传入可调用对象和参数,另一种是指定启动策略后再传入可调用对象和参数。下面是一个最简单的使用示例,启动一个异步任务计算两个数的和:

#include <iostream>
#include <future>
#include <chrono>

// 异步执行的任务函数
int add(int a, int b) {
    // 模拟耗时操作
    std::this_thread::sleep_for(std::chrono::seconds(2));
    return a + b;
}

int main() {
    // 启动异步任务,默认启动策略
    std::future<int> result = std::async(add, 10, 20);
    std::cout << "主线程继续执行其他操作" << std::endl;
    // 获取异步任务的结果,会阻塞直到任务完成
    int sum = result.get();
    std::cout << "异步任务计算结果:" << sum << std::endl;
    return 0;
}

std::async的启动策略

std::async的第一个可选参数是启动策略,有两种常用取值,分别对应不同的任务执行方式:

  • std::launch::async:强制要求任务在新线程中异步执行,不会延迟启动。
  • std::launch::deferred:延迟执行策略,任务不会立刻启动,只有当调用返回的future对象的get或者wait方法时,才会在当前线程中同步执行任务。

如果不指定启动策略,默认的策略是std::launch::async | std::launch::deferred,也就是由标准库自行决定是异步执行还是延迟执行。我们可以通过下面的代码对比两种策略的区别:

#include <iostream>
#include <future>
#include <chrono>
#include <thread>

void task() {
    std::cout << "任务执行线程ID:" << std::this_thread::get_id() << std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(1));
}

int main() {
    std::cout << "主线程ID:" << std::this_thread::get_id() << std::endl;
    
    // 使用async策略,任务在新线程执行
    std::future<void> f1 = std::async(std::launch::async, task);
    f1.get();
    
    // 使用deferred策略,任务延迟到get调用时执行
    std::future<void> f2 = std::async(std::launch::deferred, task);
    std::cout << "调用get之前,deferred任务不会执行" << std::endl;
    f2.get(); // 此时才在当前线程执行任务
    
    return 0;
}

获取异步任务的返回值与异常处理

异步任务的返回值可以通过future对象的get()方法获取,需要注意的是get()方法只能调用一次,多次调用会导致未定义行为。如果异步任务执行过程中抛出了异常,这个异常会被存储在future对象中,当调用get()方法时会重新抛出,我们可以通过try-catch块捕获异常:

#include <iostream>
#include <future>
#include <stdexcept>

int divide(int a, int b) {
    if (b == 0) {
        throw std::runtime_error("除数不能为0");
    }
    return a / b;
}

int main() {
    std::future<int> result = std::async(divide, 10, 0);
    try {
        int value = result.get();
        std::cout << "计算结果:" << value << std::endl;
    } catch (const std::exception& e) {
        std::cout << "捕获到异常:" << e.what() << std::endl;
    }
    return 0;
}

使用std::async的注意事项

  • 不要忽略std::async返回的future对象,如果future对象被销毁前没有调用get()或者wait(),在默认启动策略下,程序可能会阻塞等待异步任务完成,反而失去异步的意义。
  • 默认启动策略的不确定性可能导致问题,如果对任务执行方式有明确要求,最好显式指定std::launch::async或者std::launch::deferred
  • std::async启动的异步任务如果抛出异常且没有被捕获,程序会调用std::terminate终止,所以一定要做好异常处理。

实际开发场景示例

假设我们需要同时读取多个文件的内容,用std::async可以并行执行读取任务,提升整体效率:

#include <iostream>
#include <future>
#include <vector>
#include <string>

// 模拟读取文件内容
std::string read_file(const std::string& file_path) {
    std::this_thread::sleep_for(std::chrono::seconds(1)); // 模拟读取耗时
    return "文件" + file_path + "的内容";
}

int main() {
    std::vector<std::string> file_list = {"file1.txt", "file2.txt", "file3.txt"};
    std::vector<std::future<std::string>> futures;
    
    // 启动多个异步读取任务
    for (const auto& file : file_list) {
        futures.push_back(std::async(std::launch::async, read_file, file));
    }
    
    // 获取所有任务的结果
    for (auto& fut : futures) {
        std::cout << fut.get() << std::endl;
    }
    return 0;
}

std::asyncC++异步编程异步任务future修改时间:2026-06-23 05:57:34

免责声明:​ 已尽一切努力确保本网站所含信息的准确性。网站内容多为原创整理与精心编撰,观点力求客观中立。本站旨在免费分享,内容仅供个人学习、研究或参考使用。若引用了第三方作品,版权归原作者所有。如内容涉及您的权益,请联系我们处理。
内容垂直聚焦
专注技术核心技术栏目,确保每篇文章深度聚焦于实用技能。从代码技巧到架构设计,为用户提供无干扰的纯技术知识沉淀,精准满足专业提升需求。
知识结构清晰
覆盖从开发到部署的全链路。AI、前端、编程、数据库、服务器、建站、系统层层递进,构建清晰学习路径,帮助用户系统化掌握开发与运维所需的核心技术。
深度技术解析
拒绝泛泛而谈,深入技术细节与实践难点。无论是数据库优化还是服务器配置,均结合真实场景与代码示例进行剖析,致力于提供可直接应用于工作的解决方案。
专业领域覆盖
精准对应开发生命周期。从前端界面到后端编程,从数据库操作到服务器运维,形成完整闭环,一站式满足全栈工程师和运维人员的技术需求。
即学即用高效
内容强调实操性,步骤清晰、代码完整。用户可根据教程直接复现和应用于自身项目,显著缩短从学习到实践的距离,快速解决开发中的具体问题。
持续更新保障
专注既定技术方向进行长期、稳定的内容输出。确保各栏目技术文章持续更新迭代,紧跟主流技术发展趋势,为用户提供经久不衰的学习价值。