C++编程指南28 - 使用 std::async() 启动并发任务
一:概述
与(之前介绍的)避免使用裸指针管理资源类似,我们应该避免直接使用std::thread和std::promise,而是使用std::async 这样的工厂函数来启动并发任务。
std::async能够自动决定是创建新线程,还是重用已有的线程,从而避免直接管理std::thread带来的复杂性和潜在错误。
二:示例
1. 推荐使用std::async:
int read_value(const std::string& filename)
{std::ifstream in(filename);in.exceptions(std::ifstream::failbit);int value;in >> value;return value;
}void async_example()
{try {std::future<int> f1 = std::async(read_value, "v1.txt");std::future<int> f2 = std::async(read_value, "v2.txt");std::cout << f1.get() + f2.get() << '\n';} catch (const std::ios_base::failure& fail) {// 处理异常}
}
使用std::async 有以下几个好处:
1. 无需管理线程生命周期,std::async 自动处理线程的创建与回收。
2. 避免std::promise、std::thread 等低级 API,降低错误风险。
3. 代码更简洁,只需处理std::future,无需管理std::thread 的 join 或 detach