c++ - C++14 中 for 循环中的并行网络下载

标签 c++ networking parallel-processing c++14

我有一个链接列表,我想从中并行下载数据。

并行启动多个下载作业并获取结果的最佳方式是什么?

我的顺序循环看起来像这样:

vector<string> download_results;

for (string link : links) {
   string data = download_data(link);
   download_results.push_back(data);
}

如何并行启动 download_data(link) 同时保持 download_results 中的数据排列 与上面的顺序循环相同?

最佳答案

std::vector<std::future<std::string>> downloads;

for (string link : links) {
  auto data = std::async( std::launch::async, [link]{return download_data(link);} )
  downloads.push_back(std::move(data));
}
std::vector<std::string> download_results;
for( auto&& dl:downloads ){
  download_results.push_back(f.get());
}

这可以通过限制连接数和使用 reserve 来改善。例如,使用线程池或在达到限制时开始弹出的 future 队列。在我看来,线程池是最好的,因为它会在任何旧下载完成时排队新的下载,而队列可能会在早期的大型下载时停止。

理论上您可以编写定制的“只有 10 个下载事件”代码,但这是将业务逻辑与资源管理混合在一起。

我过去在 SO 上发布过 threaded_queuethread_pool;谷歌会找到它们。

关于c++ - C++14 中 for 循环中的并行网络下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45728352/

相关文章:

java - 如何从 Java 设置默认网关、IP 地址和子网掩码?

c# - 嵌套 Parallel.For 循环 C# 中的资源共享

r - 如何使用 plyr mdply 并行故障安全执行

c++ - 在 C++ 中使用 lambda 和 back_inserter 生成_n

c++ - 为什么与 printf 未定义行为中的转换说明符不匹配的参数?

c++ - 我可以在单独的 ssl 上下文之间重用 openssl x509store 吗?

parallel-processing - Gnu平行: nested parallelism

c++ - JDK9 Hotspot debug using gdb, causing SIGSEGV Segmentation fault in eclipse/Ubuntu 终端

linux - 替代 `tc` 命令或任何具有 `tc` 功能的 api

java - 我怎样才能关闭netty客户端?