std::async 和 std::thread 的主要区别
std::async 和 std::thread 的主要区别如下:
### 1. 获取返回值
- std::async : 可以直接获取返回值
auto future = std::async([]{ return 42; });
int result = future.get(); // 直接获取返回值
std::thread : 需要通过其他方式传递结果
int result;
std::thread t([&result]{ result = 42; });
t.join(); // 等待线程结束
### 2. 异常处理
- std::async : 可以捕获任务中的异常
auto future = std::async([]{
throw std::runtime_error("错误");
return 42;
});
try {
future.get(); // 异常会在这里被捕获
} catch(const std::exception& e) {
// 处理异常
}
std::thread : 异常需要在线程内处理
std::thread t([]{
try {
throw std::runtime_error("错误");
} catch(...) {
// 必须在线程内处理
}
});
### 3. 线程管理
- std::async : 自动管理线程的创建和销毁
- std::thread : 需要手动调用 join() 或 detach()
### 4. 使用场景
- std::async : 适合
- 需要返回值的任务
- 需要异常处理
- 简单的异步操作
- std::thread : 适合
- 需要更细粒度控制的场景
- 长期运行的任务
- 需要直接控制线程的场景
async使用
// 1. 一定在新线程中执行
auto f1 = std::async(std::launch::async, []{ return 42; });
// 2. 一定延迟到get()调用时在当前线程执行
auto f2 = std::async(std::launch::deferred, []{ return 42; });
// 3. 系统自动选择执行方式
auto f3 = std::async([]{ return 42; });
返回值是std::future<xxx>
调用get方法获取结果
int ret = f1.get();