推荐答案
// www.javascriptcn.com code example
#include <iostream>
#include <future>
#include <thread>
#include <chrono>
int compute() {
std::this_thread::sleep_for(std::chrono::seconds(2)); // 模拟耗时操作
return 42;
}
int main() {
// 使用 std::async 启动异步任务
std::future<int> result = std::async(std::launch::async, compute);
// 在主线程中执行其他操作
std::cout << "Doing other work..." << std::endl;
// 获取异步任务的结果
int value = result.get();
std::cout << "Result: " << value << std::endl;
return 0;
}本题详细解读
1. std::async 的基本用法
std::async 是 C++11 引入的一个用于异步执行任务的函数模板。它允许你以异步的方式启动一个任务,并返回一个 std::future 对象,该对象可以用来获取任务的返回值。
std::future<int> result = std::async(std::launch::async, compute);
std::launch::async:指定任务以异步方式执行,即在新线程中执行。compute:要执行的函数或可调用对象。
2. std::future 的使用
std::future 是一个模板类,用于表示一个异步操作的结果。你可以通过调用 get() 方法来获取异步操作的结果。如果结果尚未准备好,get() 会阻塞当前线程,直到结果可用。
int value = result.get();
3. 异步任务的执行
在 compute 函数中,我们模拟了一个耗时操作(如网络请求、文件 I/O 等),通过 std::this_thread::sleep_for 来模拟 2 秒的延迟。
int compute() {
std::this_thread::sleep_for(std::chrono::seconds(2)); // 模拟耗时操作
return 42;
}4. 主线程的其他操作
在异步任务执行的同时,主线程可以继续执行其他操作,而不需要等待异步任务完成。
std::cout << "Doing other work..." << std::endl;
5. 获取异步任务的结果
当主线程需要异步任务的结果时,可以通过 result.get() 来获取。如果异步任务尚未完成,主线程会阻塞,直到任务完成并返回结果。
int value = result.get(); std::cout << "Result: " << value << std::endl;
6. 总结
std::async 提供了一种简单的方式来执行异步任务,并且通过 std::future 可以方便地获取任务的结果。这种方式非常适合在需要并行处理任务的场景中使用。