C++ 中的多个异步调用

Tur*_*len 6 c++ multithreading c++11

我想多次调用异步方法。一个简化的例子如下所示:

size_t counter(std::string &s)
{
    return s.size();
}

void stringCountAccumulator()
{
    std::vector<std::string> foos = {"this", "is", "spartaa"};
    size_t total = 0;
    for (std::string &s : foos)
    {
        std::future<size_t> fut = std::async(
            std::launch::async,
            counter, s);

        total += fut.get();
    }
    std::cout << "Total: " << total;
}
Run Code Online (Sandbox Code Playgroud)

看起来, fut.get() 阻止了其他未来的调用。如何在 C++ 中实现这个问题?我需要在单独的线程中调用一个函数。此函数“返回”一个值。

Yak*_*ont 7

void stringCountAccumulator()
{
  std::vector<std::string> foos = {"this", "is", "spartaa"};
  std::vector<std::future<size_t>> calcs;
  for (auto&& s : foos) {
    calcs.push_back( std::async(
      std::launch::async,
      counter, s)
    );
  }
  std::size_t total = 0;
  for (auto&& fut:calcs)
    total += fut.get();
  std::cout << "Total: " << total << "\n";
}
Run Code Online (Sandbox Code Playgroud)

.get()正在阻塞。所以在所有任务都排队之前不要阻塞。

另一种计划是编写/查找线程池,并让每个任务更新一个可能的原子(或互斥保护)计数器。

有一个完成的任务计数器被保护(同样,可能是原子的)。

有一个承诺(总数),当最后一个任务完成时(由最后一个任务完成)。

从那个承诺返回未来。现在你有一个 Future 代表整个线程池,计算它们的值并将其相加,具有大量并发性。

一些框架,比如微软的 ppl,有一个系统,它可以为你做这样的事情;您有返回值的任务,以及组合这些值的函数对象,并从中获得组合的结果。