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

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值