C 中多个async调用

Multiple Async Calls in C++

本文关键字:async 调用      更新时间:2023-10-16

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

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

看来,fut.get()阻止了其他未来的呼叫。如何在C 中实现此问题?我需要在单独的线程中调用功能。此功能"返回"一个值。

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

.get()正在阻止。因此,除非您已经完成所有任务,

才能阻止。

替代计划是编写/查找线程池,并让每个任务更新可能是原子(或静音守护)计数器。

有一个完成任务的柜台(再次,可能是原子)。

有一个(总计)的承诺,您在完成最后一项任务后要实现(完成了最后一个任务)。

从那个诺言中返回未来。现在,您有一个未来代表整个线程池计算其价值并增加了很多并发。

某些框架,例如Microsoft的PPL,具有一个为您提供类似的系统。您拥有返回值的任务,并且是将值结合的函数对象,并从中获得组合的结果。

您还需要声明StringCountAccumulator()将异步执行。也只有在未来准备就绪时才致电Future :: get()。这是代码段:

 std::future<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);
        while (!fut.is_ready() ) ;
        total += fut.get();
    }
   std::cout << "Total: " << total;
  }