async
在C++中,async 是标准库中的一种异步操作工具,用于启动异步任务。它是C++11引入的一部分,位于头文件 中。std::async 提供了一种轻量级的方式来创建线程或异步任务并获取结果。
定义
std::async 是一个模板函数,定义如下:
template< class Function, class... Args >
std::future<typename std::result_of<Function(Args...)>::type>
async( std::launch policy, Function&& f, Args&&... args );
policy: 指定如何启动任务,有以下选项:
std::launch::async: 强制在新线程中异步执行。
std::launch::deferred: 延迟执行,直到调用 get 或 wait。
std::launch::async | std::launch::deferred(默认): 由实现决定是否创建新线程或延迟执行。
f: 要执行的函数。
args: 函数的参数。
功能与作用
- 任务并行: 提高程序的运行效率。
- 简化多线程操作: 管理线程及其结果的同步。
- 提供线程返回值: 使用 std::future 获取异步任务的返回值。
async参考代码示例
以下代码展示了 std::async 的基本用法:
#include <iostream>
#include <future>
#include <thread>
#include <chrono>
// 一个耗时的任务
int longTask(int duration, const std::string& taskName) {
std::cout << "Task " << taskName << " started in thread "
<< std::this_thread::get_id() << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(duration));
std::cout << "Task " << taskName << " finished." << std::endl;
return duration * 2;
}
int main() {
// 启动异步任务,指定为 std::launch::async 强制使用新线程
auto future1 = std::async(std::launch::async, longTask, 3, "A");
// 启动延迟任务(deferred)
auto future2 = std::async(std::launch::deferred, longTask, 2, "B");
// 主线程的任务
std::cout << "Main thread is running in thread "
<< std::this_thread::get_id() << std::endl;
// 获取结果
int result1 = future1.get(); // 立即启动并等待完成
std::cout << "Result of Task A: " << result1 << std::endl;
int result2 = future2.get(); // 延迟任务在这里执行
std::cout << "Result of Task B: " << result2 << std::endl;
return 0;
}
async参考代码输出结果
Main thread is running in thread 140147801564992
Task A started in thread 140147783354112
Task A finished.
Result of Task A: 9
Task B started in thread 140147801564992
Task B finished.
Result of Task B: 4
async参考代码解释
- longTask: 一个模拟耗时操作的函数。
- std::async 的两种策略:
std::launch::async: 强制新线程执行任务。
std::launch::deferred: 延迟任务,只有在调用 get() 或 wait() 时才执行。 - std::future:
用于存储异

最低0.47元/天 解锁文章
1424

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



