C 中多个async调用
Multiple Async Calls in C++
我想多次调用异步的方法。简化的示例如下:
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;
}
相关文章:
- 使用用户定义的参数调用future/async并调用类方法
- std::async 如何工作:为什么它会调用这么多次复制/移动?
- std::async 不会立即调用
- 在Visual Studio中,与std::async一起使用时不调用"thread_local"变量"析构函数,这是一个错误吗?
- 为什么使用线程池时嵌套调用 boost::async 会阻塞?
- 使用 std::async 调用模板函数的正确方法是什么?
- C 中多个async调用
- 有没有一种方法可以从C++中调用"async"python方法
- 当Qt-Slot位于通过std::async创建的线程上时,它不会被调用
- 应该在游戏循环c++中调用std::async吗
- 如何使用“std::async”在互斥锁保护循环中调用函数
- 使用C++11期货:std::async崩溃的嵌套调用:编译器/标准库错误
- 可以 std::async 调用 std::function 对象
- 为什么调用 std::async 后的时间成本为 0 秒
- 在高频率下调用std::async可以吗
- 用std::async调用带unique_ptr类型的函数
- 为什么std::async即使指定了std::launch::async标志,也要同步调用函数?
- 使用std::async从线程调用函数
- 用线程池替换许多std::async调用
- 如果父/主线程死亡,std::async调用会发生什么?