我有一个链接列表,我想从中并行下载数据。
并行启动多个下载作业并获取结果的最佳方式是什么?
我的顺序循环看起来像这样:
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_queue
和 thread_pool
;谷歌会找到它们。
关于c++ - C++14 中 for 循环中的并行网络下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45728352/