#include <iostream>
#include <future>
#include <thread>
// 定义一个简单的函数,用于异步执行
int compute(int a, int b) {
std::this_thread::sleep_for(std::chrono::seconds(2)); // 模拟耗时操作
return a + b;
}
int main() {
// 使用 std::async 启动异步任务
std::future<int> result = std::async(std::launch::async, compute, 10, 20);
// 可以在这里做其他事情,模拟并发操作
std::cout << "Waiting for the result...\n";
// 获取异步任务的结果,如果任务未完成则会阻塞等待
int sum = result.get();
std::cout << "Result: " << sum << '\n';
return 0;
}
std::async:用于启动一个异步任务。它可以立即返回一个 std::future 对象,该对象可以用来获取异步任务的返回值。std::launch::async:指定任务应该在新线程中异步执行。如果不指定,默认情况下,std::async 可能会选择同步或异步执行。std::future:表示异步操作的结果。通过调用 get() 方法可以获取结果,如果任务还未完成,get() 会阻塞当前线程直到任务完成。compute 函数:模拟了一个耗时的操作,并返回两个整数的和。这个示例展示了如何使用 C++ 的 std::async 来启动一个异步任务,并在主线程中等待其结果。
上一篇:c++插件
下一篇:operator在c++中的用法
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站