c++11 async

定义

async可可以异步地运行一个函数f,返回一个拥有其结果的future对象。传给async()可以是任何类型的callable object,可以是函数、成员函数、函数对象或lambda。

可选的运行策略

anync:以新线程异步执行
deferred:调用线程上首次请求结果时执行

使用

#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;
} 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值