C++11 async

一 前面
  • C++11开始,对并发提供了强有力的支持,本文介绍其中的 std::async。
  • 头文件< future >
二 定义
template< class Function, class... Args>
std::future<std::result_of_t<std::decay_t<Function>(std::decay_t<Args>...)>>
    async( Function&& f, Args&&... args );(1)(C++11)(C++17)
template< class Function, class... Args>
std::future<std::invoke_result_t<std::decay_t<Function>, std::decay_t<Args>...>>
    async( Function&& f, Args&&... args );(1)(C++17)(C++20)
template< class Function, class... Args>
[[nodiscard]]
std::future<std::invoke_result_t<std::decay_t<Function>,
                                 std::decay_t<Args>...>>
    async( Function&& f, Args&&... args );(1)(C++20)	
template< class Function, class... Args >
std::future<std::result_of_t<std::decay_t<Function>(std::decay_t<Args>...)>>
    async( std::launch policy, Function&& f, Args&&... args );(2)(C++11)(C++17)
template< class Function, class... Args >
std::future<std::invoke_result_t<std::decay_t<Function>,
                                 std::decay_t<Args>...>>
    async( std::launch policy, Function&& f, Args&&... args );(2)(C++17)(C++20)
template< class Function, class... Args >
[[nodiscard]]
std::future<std::invoke_result_t<std::decay_t<Function>,
                                 std::decay_t<Args>...>>
    async( std::launch policy, Function&& f, Args&&... args );(2)(C++20)
  • 异步运行一个函数 f(有可能在新线程中执行),并返回保有其结果的 std::future。
  • 传给async()可以是任何类型的callable object,可以是函数、成员函数、函数对象或lambda。
  • 运行策略policy
enum class launch : {
    async, // 运行新线程,以异步执行任务
    deferred, // 调用方线程上首次请求其结果时执行任务(惰性求值)
}; (C++11)

  • 对于定义(1),采用哪种运行策略取决于实现。
  • 返回类型 future, 请参见此前文章 C++11 future
三 例子
#include <algorithm>
#include <future>
#include <iostream>
#include <mutex>
#include <numeric>
#include <string>
#include <vector>

std::mutex m;
struct X {
  void foo(int i, const std::string& str) {
    std::lock_guard<std::mutex> lk(m);
    std::cout << str << ' ' << i << '\n';
  }
  void bar(const std::string& str) {
    std::lock_guard<std::mutex> lk(m);
    std::cout << str << '\n';
  }
  int operator()(int i) {
    std::lock_guard<std::mutex> lk(m);
    std::cout << i << '\n';
    return i + 10;
  }
};

template <typename RandomIt>
int parallel_sum(RandomIt beg, RandomIt end) {
  auto len = end - beg;
  if (len < 1000)
    return std::accumulate(beg, end, 0);

  RandomIt mid = beg + len / 2;
  auto handle =
      std::async(std::launch::async, parallel_sum<RandomIt>, mid, end);
  int sum = parallel_sum(beg, mid);
  return sum + handle.get();
}

int main() {
  std::vector<int> v(10000, 1);
  std::cout << "The sum is " << parallel_sum(v.begin(), v.end()) << '\n';

  X x;
  // 以默认策略调用 x.foo(42, "Hello"): 可能同时打印 "Hello 42" 或延迟执行
  auto a1 = std::async(&X::foo, &x, 42, "Hello");

  // 以 deferred 策略调用 x.bar("world!"):
  // 调用 a2.get() 或 a2.wait() 时打印 "world!"
  auto a2 = std::async(std::launch::deferred, &X::bar, x, "world!");

  // 以 async 策略调用 X()(43): 同时打印 "43"
  auto a3 = std::async(std::launch::async, X(), 43);
  a2.wait();                      // 打印 "world!"
  std::cout << a3.get() << '\n';  // 打印 "53"

  std::cin.get();
  return 0;
} 

  • 结果
// 每次运行顺序可能不同
The sum is 10000
Hello 42
world!
43
53
四 参考

cppreference- async

<think>好的,用户想了解C++async函数的用法和相关问题。首先,我需要回忆一下C++11引入的std::async以及相关的功能。std::async是用来异步执行函数,并返回一个std::future对象,以便在之后获取结果。用户可能需要知道基本用法、参数选项、异常处理以及线程池的关系。 根据用户提供的引用内容,特别是引用[2]提到线程池的实现原理和回调函数的使用,用户可能对async与线程池的配合使用感兴趣。需要说明std::async默认是否使用线程池,或者如何结合两者。 接下来,我需要整理async的常用方法,比如启动策略(std::launch::async和std::launch::deferred),以及如何通过future获取结果。还需要举几个例子,比如计算斐波那契数列或者处理多个任务,这样用户能更直观地理解。 另外,用户可能关心异常处理,因为在异步任务中异常无法直接捕获,必须通过future对象来获取。这部分需要详细说明。 还要注意用户提到的引用[1]中的ROS2节点创建,虽然可能与async没有直接关系,但可能在异步任务处理的应用场景中有联系,比如在ROS2中使用async处理回调,但这里可能需要避免混淆,专注于标准库的async。 需要确保回答结构清晰,分点说明用法、示例、注意事项,并生成相关问题。同时检查是否符合格式要求,比如行内公式用$...$,代码块正确,引用标识正确添加。</think>### C++async函数用法详解 #### 一、基本概念 C++11引入的$std::async$函数用于异步执行任务,返回一个$std::future$对象存储计算结果。其核心特性包括: 1. 支持延迟执行($std::launch::deferred$) 2. 强制异步执行($std::launch::async$) 3. 自动回收线程资源[^2] #### 二、核心用法 ```cpp #include <future> #include <iostream> int add(int a, int b) { return a + b; } int main() { // 启动异步任务 auto future = std::async(std::launch::async, add, 10, 20); // 获取结果(阻塞等待) std::cout << "Result: " << future.get() << std::endl; return 0; } ``` #### 三、启动策略对比 | 策略类型 | 行为特征 | |--------------------------|-----------------------------------| | $std::launch::async$ | 强制创建新线程执行 | | $std::launch::deferred$ | 延迟到调用get()/wait()时同步执行 | #### 四、高级应用场景 1. **并行计算** ```cpp auto future1 = std::async([]{ return compute(1); }); auto future2 = std::async([]{ return compute(2); }); auto result = future1.get() + future2.get(); ``` 2. **异常处理** ```cpp try { auto future = std::async([]{ throw std::runtime_error("error"); }); future.get(); } catch(const std::exception& e) { std::cerr << e.what() << std::endl; } ``` 3. **结合线程池使用** 虽然$std::async$本身不直接管理线程池,但可通过自定义分配器实现类似效果: ```cpp // 使用线程池执行异步任务 auto future = std::async(thread_pool_executor, heavy_task); ``` #### 五、性能注意事项 1. 默认策略可能重用线程(取决于实现) 2. 频繁创建任务应考虑线程池方案 3. 返回值类型必须可拷贝或可移动
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值