Can each Iteration of a for loop/for_each be done in parallel? (C++11)

巧了我就是萌 提交于 2019-12-22 04:05:14

问题


I'm iterating over a vector of structs and processing each struct individually.
It looks something like this:

for_each(begin(data),end(data),DoTask);
//assume "data" is std::vector<DataT>  
//assume DoTask is a function that takes a DataT by reference

The code is significantly slow because DoTask connects to particular websites and analyzes HTML.
What would be the best way to speed this up?
My goal is to analyze multiple DataTs at the same time.
I'm very new to threading, but std::async and std::future look promising.


回答1:


You can do something like this

for(T& d : data) std::thread(DoTask, d).detach();

Or you can use something more complicated like Intel's Thread Building Blocks and the parallel_for (isn't that the name?) function thereof.




回答2:


Are you using GCC? Recent versions have a parallel version of for_each (see here for how to use it).




回答3:


You can always use The Parallel Patterns Library (PPL) from Microsoft, if you target Windows/VS2010 (or later). It has parallel_for_each:

parallel_for_each(values.begin(), values.end(), [] (int& value)
{
  value *= 2;
});


来源:https://stackoverflow.com/questions/10155457/can-each-iteration-of-a-for-loop-for-each-be-done-in-parallel-c11

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!