C++ 标准库异步编程示例(一)

C++ 标准库异步编程示例(一) 🚀

主线程
std::promise
std::async
std::future
std::future
设置值/异常
获取结果
线程间通信
同步执行点

🧠 技术原理概述

上面的流程图展示了异步编程的基本原理:主线程创建std::promise或调用std::async启动后台任务,这些操作返回std::future对象,用于等待和获取后台线程的执行结果。整个过程实现了:

  1. 线程间的解耦
  2. 高效的任务管理
  3. 安全的结果传输
  4. 便捷的异常处理

🔧 1. std::promise 和 std::future 示例

🔒 1.1. 无异常传递

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

// 线程函数:通过promise设置值
void setValue(std::promise<int> prom) {
    std::this_thread::sleep_for(std::chrono::seconds(1)); // 模拟耗时操作
    prom.set_value(42); // 设置计算结果
}

int main() {
    // 创建promise和future
    std::promise<int> prom;
    std::future<int> fut = prom.get_future();

    // 启动线程传递promise(需使用std::move)
    std::thread t(setValue, std::move(prom));

    try {
        // 主线程阻塞等待结果
        int result = fut.get(); 
        std::cout << "Result from promise: " << result << std::endl;
    }
    catch (const std::runtime_error& e) {
        std::cerr << "Exception: " << e.what() << std::endl;
    }

    t.join();
    return 0;
}

说明:此示例展示了线程间安全的值传递。主线程创建promise对象并从中获取future,然后启动新线程并移交promise所有权。工作线程完成计算后设置结果,主线程通过future.get()等待并获取结果。

⚠️ 1.2. 异常传递

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

// 线程函数:通过promise设置异常
void setValue(std::promise<int> prom) {
    std::this_thread::sleep_for(std::chrono::seconds(1)); 
    // 创建并设置异常
    prom.set_exception(
        std::make_exception_ptr(std::runtime_error("Test exception"))
    ); 
}

int main() {
    std::promise<int> prom;
    std::future<int> fut = prom.get_future();
    std::thread t(setValue, std::move(prom));

    try {
        int result = fut.get(); 
        std::cout << "Result: " << result << std::endl;
    }
    catch (const std::exception& e) {
        std::cerr << "Caught exception: " << e.what() << std::endl;
    }

    t.join();
    return 0;
}

说明:此例展示C++异步异常处理机制。工作线程通过promise.set_exception()传递异常对象,主线程在调用future.get()时会抛出该异常。注意:

  • 使用std::make_exception_ptr()封装异常
  • 捕获std::exception基类而非特定类型
  • 异常传递不会造成程序崩溃,而是可控的错误处理
主线程std::promisestd::future工作线程创建promise获取future创建线程,移交promiseset_value/set_exceptionget() 阻塞等待结果返回值抛出异常alt[成功][异常]主线程std::promisestd::future工作线程

⚡ 2. std::async 异步任务示例

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

// 异步任务函数
int asyncTask() {
    std::cout << "Async task running in thread: "
              << std::this_thread::get_id() << std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(2));
    return 100;
}

int main() {
    // 启动异步任务(异步执行策略)
    std::future<int> fut = std::async(std::launch::async, asyncTask);

    std::cout << "Main thread: " << std::this_thread::get_id()
              << " doing other work..." << std::endl;

    // 获取异步结果(阻塞直到完成)
    int result = fut.get();
    std::cout << "Async result: " << result << std::endl;

    return 0;
}

说明:该示例展示std::async的高级抽象,自动管理线程生命周期:

  1. 使用std::launch::async策略确保立即异步执行
  2. 主线程与异步任务并发执行
  3. future.get()提供同步点,等待任务完成
  4. 隐式的资源管理,避免手动线程创建/销毁

执行策略对比

策略行为适用场景
std::launch::async立即创建新线程执行需要真正并行执行时
std::launch::deferred延迟到get()时在当前线程执行需要按需执行或避免线程开销
默认策略实现定义(通常是async)一般使用

🔗 3. 完整组合测试(promise + async + future)

#include <iostream>
#include <thread>
#include <future>
#include <vector>
#include <numeric>
#include <cmath>

// 使用promise传递复杂结果
void calculateSum(std::promise<int> && prom, std::vector<int> data) {
    std::cout << "Calculate sum started..." << std::endl;
    int sum = std::accumulate(data.begin(), data.end(), 0);
    prom.set_value(sum); 
    std::cout << "Sum calculated: " << sum << std::endl;
}

// 使用async包装的异步任务
std::future<int> asyncMultiply(int a, int b) {
    return std::async([=] {
        std::cout << "Multiplication started..." << std::endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
        return a * b;
    });
}

int main() {
    // Part 1: promise/future传递数据
    std::promise<int> sumPromise;
    auto sumFuture = sumPromise.get_future();
    std::thread worker(calculateSum, std::move(sumPromise),
                      std::vector<int>{1, 2, 3, 4, 5});

    // Part 2: 同时执行多个async任务
    auto fut1 = asyncMultiply(6, 7);
    auto fut2 = asyncMultiply(8, 9);

    // 等待所有结果
    std::cout << "Sum result: " << sumFuture.get() << std::endl;
    std::cout << "Multiply results: " << fut1.get() << ", " << fut2.get() << std::endl;

    worker.join();
    return 0;
}

说明:此示例综合应用了C++异步编程组件:

  1. 多线程协同

    • 主线程、手动创建线程、async线程协同工作
    • 不同任务的执行时间各不相同(1秒、0.5秒)
  2. 并发模型

    2025-07-272025-07-272025-07-272025-07-272025-07-272025-07-272025-07-272025-07-272025-07-272025-07-272025-07-272025-07-272025-07-272025-07-272025-07-272025-07-27主线程 求和任务 乘法任务1 乘法任务2 任务执行任务时间线
  3. 安全共享状态

    • std::promisestd::future配对,提供线程安全的数据传输通道
    • future.get()自动同步,确保结果就绪后才继续执行

🛠 编译与执行

使用支持C++11及以上标准的编译器:

# 使用GCC (Linux/macOS)
g++ -std=c++11 -pthread test.cpp -o async_demo
./async_demo

# 使用MSVC (Windows)
cl /EHsc /std:c++11 test.cpp
test.exe

📊 预期输出模式

Main thread : 140737295888192 doing other work...
Async task running in thread : 140737295884032
Async result : 100

Sum result : 15
Multiply results : 42, 72

注意输出特性

  1. 线程ID每次运行可能不同
  2. 日志输出顺序不固定(取决于线程调度)
  3. 计算结果值始终一致
  4. 异常情况会中断正常流程并显示错误信息

🔍 技术关键点深度解析

🧩 std::promise 内部机制

std::promise内部维护一个共享状态(shared state),包含:

  • 就绪状态标志
  • 存储的值或异常对象
  • 关联的future对象

当调用set_value()set_exception()时:

  1. 原子设置就绪标志
  2. 存储结果到共享状态
  3. 唤醒所有等待的线程

⏳ std::future 阻塞语义

future.get()方法的操作流程:

调用get
结果就绪?
返回结果
阻塞调用线程
等待通知
被唤醒

⚙️ std::async 实现策略

编译器实现std::async时可能采用:

  • 线程池技术减少创建开销
  • Work-stealing算法负载均衡
  • 基于当前硬件并行度的自适应调度

📌 实践建议

  1. 所有权传递

    • 始终使用std::move传递std::promise
    • 确保promise在所有执行路径中被设置
  2. 异常安全

    try {
        // 可能抛出异常的代码
    } catch(...) {
        prom.set_exception(std::current_exception());
    }
    
  3. 性能优化

    // 仅当需要返回值时调用get()
    if(fut.wait_for(0s) == std::future_status::ready) {
        auto result = fut.get();
    }
    
  4. 线程限制

    • 避免过多并发线程
    • 推荐数量:std::thread::hardware_concurrency() - 1
  5. 调试提示

    • 使用gdb的info threads查看线程状态
    • 在Clang中启用-fsanitize=thread检测数据竞争
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值