C++ 标准库异步编程示例(一) 🚀
🧠 技术原理概述
上面的流程图展示了异步编程的基本原理:主线程创建std::promise或调用std::async启动后台任务,这些操作返回std::future对象,用于等待和获取后台线程的执行结果。整个过程实现了:
- 线程间的解耦
- 高效的任务管理
- 安全的结果传输
- 便捷的异常处理
🔧 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基类而非特定类型 - 异常传递不会造成程序崩溃,而是可控的错误处理
⚡ 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的高级抽象,自动管理线程生命周期:
- 使用
std::launch::async策略确保立即异步执行 - 主线程与异步任务并发执行
future.get()提供同步点,等待任务完成- 隐式的资源管理,避免手动线程创建/销毁
执行策略对比:
| 策略 | 行为 | 适用场景 |
|---|---|---|
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++异步编程组件:
-
多线程协同:
- 主线程、手动创建线程、async线程协同工作
- 不同任务的执行时间各不相同(1秒、0.5秒)
-
并发模型:
-
安全共享状态:
std::promise和std::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
注意输出特性:
- 线程ID每次运行可能不同
- 日志输出顺序不固定(取决于线程调度)
- 计算结果值始终一致
- 异常情况会中断正常流程并显示错误信息
🔍 技术关键点深度解析
🧩 std::promise 内部机制
std::promise内部维护一个共享状态(shared state),包含:
- 就绪状态标志
- 存储的值或异常对象
- 关联的future对象
当调用set_value()或set_exception()时:
- 原子设置就绪标志
- 存储结果到共享状态
- 唤醒所有等待的线程
⏳ std::future 阻塞语义
future.get()方法的操作流程:
⚙️ std::async 实现策略
编译器实现std::async时可能采用:
- 线程池技术减少创建开销
- Work-stealing算法负载均衡
- 基于当前硬件并行度的自适应调度
📌 实践建议
-
所有权传递
- 始终使用
std::move传递std::promise - 确保promise在所有执行路径中被设置
- 始终使用
-
异常安全
try { // 可能抛出异常的代码 } catch(...) { prom.set_exception(std::current_exception()); } -
性能优化
// 仅当需要返回值时调用get() if(fut.wait_for(0s) == std::future_status::ready) { auto result = fut.get(); } -
线程限制
- 避免过多并发线程
- 推荐数量:
std::thread::hardware_concurrency() - 1
-
调试提示
- 使用gdb的
info threads查看线程状态 - 在Clang中启用
-fsanitize=thread检测数据竞争
- 使用gdb的
&spm=1001.2101.3001.5002&articleId=149674660&d=1&t=3&u=f8cff00a8c8649cfa3903efb29737ad0)
2万+

被折叠的 条评论
为什么被折叠?



