C++11引入了std::async,用于简化异步任务的创建与管理。本文将详细介绍std::async的功能、用法及其与其他并行编程工具的区别。
什么是std::async?
std::async是C++11标准库中的一个函数,用于异步执行任务,并返回一个std::future对象以获取任务的结果。它提供了一种简单而灵活的方式来创建并行任务,而无需手动管理线程。
核心优势
- 自动管理线程:无需手动创建和管理std::thread。
- 结果同步:通过std::future对象,提供了一种简便的方式来获取异步任务的结果。
- 错误处理:std::future可以捕捉异步任务中抛出的异常,使得错误处理更加容易。
函数声明
template <typename F, typename... Args>
std::future<typename std::result_of<F(Args...)>::type>
std::async(std::launch policy, F&& f, Args&&... args);
- policy:指定任务执行策略
- std::launch::async:在新线程中异步执行
- std::launch::deferred:延迟执行,在调用std::future::get()或std::future::wait()时执行
- std::launch::async | std::launch::deferred:系统根据负载决定是否异步执行
std::async与std::thread的区别
- 线程创建:std::thread显式地创建一个新线程,而std::async在使用std::launch::async策略时创建新线程,使用std::launch::deferred策略时则不会立即创建线程。
- 返回值:std::async返回一个std::future对象,用于获取任务结果;而std::thread不返回值。
- 异常处理:std::future可以捕捉异步任务中的异常;而std::thread需要手动处理异常。
- 任务管理:std::async自动管理任务的启动和同步;std::thread需要手动管理线程的生命周期。
使用场景
- 计算密集型任务:在后台执行长时间运行的计算任务。
- IO操作:例如文件读取、网络请求等,可以在后台异步执行,避免阻塞主线程。
- 并行任务:需要同时运行多个独立任务,并在它们完成后获取结果。
示例代码
int do_work_async(int a) {
return a * a;
}
void task1() {
std::future<int> result = std::async(std::launch::async, do_work_async, 10);
std::cout << "Result: " << result.get() << std::endl;
}
异常处理
void do_work_exception() {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
throw std::runtime_error("An error occurred in task");
}
void exception() {
try {
auto future = std::async(std::launch::async, do_work_exception);
throw std::runtime_error("An error occurred before calling future.get()");
future.get();
} catch (const std::exception& e) {
std::cerr << "Caught exception: " << e.what() << std::endl;
}
}
使用shared_future
std::shared_future<int> sharedFutureFun(int val) {
return std::async(std::launch::async, [val] { return val; }).share();
}
void sharedFutureTest() {
auto sharedFuture = sharedFutureFun(199);
std::cout << "sharedFuture: " << sharedFuture.get() << std::endl;
sharedFuture.wait();
}
总结
std::async提供了一种高效且易用的方式来处理并行任务,简化了线程管理、结果同步和异常处理。与std::thread相比,std::async在很多情况下更为便捷,是进行异步编程的强大工具。
通过本文的介绍,希望能帮助你更好地理解和使用std::async来编写高效的并行程序。