c++怎么使用std::async和std::future_c++异步任务与并发执行机制

std::async和std::future用于异步任务,通过launch策略启动函数并返回future对象,调用get()获取结果,支持并发执行与超时控制,需注意get()仅能调用一次且避免析构阻塞。

在C++中,std::asyncstd::future 是实现异步任务和并发执行的重要工具,它们定义在 头文件中。通过这两个机制,你可以轻松启动后台任务并获取其结果,而无需手动管理线程。

std::async 的基本用法

std::async 用于启动一个异步任务,返回一个 std::future 对象,该对象可用于在将来获取任务的返回值。

基本语法:

std::future result = std::async(launch_policy, function, args...);

其中:

  • launch_policy:指定任务的启动策略,可选 std::launch::async(强制异步执行)或 std::launch::deferred(延迟执行,调用 get 时才运行)
  • function:要异步执行的函数或可调用对象
  • args...:传递给函数的参数

如果不指定策略,系统会根据情况自动选择。

使用 std::future 获取异步结果

std::future 表示一个可能还未完成的计算结果。调用其 get() 方法会阻塞当前线程,直到结果可用。

示例:

#include iostream>
#include
#include

int long_computation() {
std::this_thread::sleep_for(std::chrono::seconds(2));
return 42;
}

int main() {
auto future_result = std::async(std::launch::async, long_computation);
std::cout int value = future_result.get(); // 阻塞等待结果
std::cout return 0;
}

这段代码会在后台执行耗时函数,主线程可以继续处理其他逻辑,最后通过 get() 获取结果。

并发执行多个任务

你可以同时启动多个 std::async 任务,实现真正的并发执行。

示例:

#include stream>
#include
#include

int task(int id) {
std::this_thread::sleep_for(std::chrono::milliseconds(500 * (id + 1)));
return id * 10;
}

int main() {
std::vector<:future>> futures;

for (int i = 0; i futures.push_back(std::async(std::launch::async, task, i));
}

for (auto& fut : futures) {
std::cout }
return 0;
}

三个任务并发运行,虽然执行时间不同,但总体耗时小于串行执行。

注意事项与最佳实践

使用 std::asyncstd::future 时需注意以下几点:

  • 每个 std::futureget() 只能调用一次,再次调用会抛出异常
  • 若不调用 get()wait(),析构时可能会阻塞(尤其是使用 async 策略时)
  • 不能复制 std::future,只能移动
  • 对于需要多次获取结果的场景,可考虑使用 std::shared_future
  • 避免长时间阻塞主线程,必要时可用 wait_forwait_until 设置超时

基本上就这些。合理使用 std::async 能简化多线程编程,让异步任务更清晰可控。