std::async异步处理耗时任务"/>
通过std::async异步处理耗时任务
在需要执行长时间运行的操作时,可以将任务放入一个独立的异步线程中,以避免阻塞主线程并提高程序的响应性。
std::async 是 C++ 中的一个标准库函数,用于创建异步任务,它可以在单独的线程中执行给定的函数或可调用对象,并返回一个 std::future 对象,用于获取异步任务的结果。
std::async 的语法如下:
template <class Fn, class... Args>
std::future<typename std::result_of<Fn(Args...)>::type> async(Fn&& fn, Args&&... args);
- Fn:要执行的函数或可调用对象。
- Args:函数或对象的参数。
- fn:要执行的函数或对象。
- args:传递给函数或对象的参数。
以下是一个示例程序,演示了 std::async 的用法:
#include <iostream>
#include <future>// 长时间运行的操作,返回计算结果
int longRunningOperation() {std::this_thread::sleep_for(std::chrono::seconds(5)); // 模拟长时间运行return 42;
}int main() {// 异步执行长时间运行的操作std::future<int> result = std::async(std::launch::async, longRunningOperation);// 主线程可以继续执行其他任务std::cout << "Main thread is doing other work..." << std::endl;// 等待长时间运行操作的结果int operationResult = result.get();std::cout << "Long running operation result: " << operationResult << std::endl;return 0;
}
在这个示例中,有一个长时间运行的操作 longRunningOperation,它在这里被模拟为休眠 5 秒钟,然后返回结果 42。使用 std::async 函数将该操作异步执行,并通过 std::future 对象获取其结果。在主线程中,可以继续执行其他任务,而不必等待长时间运行的操作完成。最后,我们通过 result.get() 等待并获取异步操作的结果。
std::async 函数有几个执行策略(launch policies)可以选择:
- std::launch::async:指定在新线程中执行异步任务。
- std::launch::deferred:指定在调用 std::future 的 get() 或 wait() 函数时执行异步任务。
- std::launch::async | std::launch::deferred:允许实现根据情况自行选择执行策略。
更多推荐
通过std::async异步处理耗时任务
发布评论