并行操作 std::vector 的不同元素
假设我有一个 std::vector
。该向量很大(> 1000 个元素),并且每个 Object*
都需要对其进行大量计算。然后,对每个元素运行每个计算的 for 循环可以轻松并行化。事实上,我可以并行处理所有 1000 个元素以获得最大加速(“令人尴尬的并行?”)
现在我想知道两件事:
1)读取和写入 a 的不同元素是否安全std::vector
没有锁? (不修改向量本身!)
2)是否有简单的方法或约定或模式可以遵循来剪切 for 循环并分派到线程?
Say I have a std::vector<Object*>
. The vector is large ( > 1000 elements) and each Object*
needs to have extensive computation done on it. The for loop that runs each the computation on each element then, can be easily parallelized. In fact, I could process all 1000 elements in parallel for maximum speedup ("embarrassingly parallel?")
Now I'm wondering 2 things:
1) Is it safe to read and write to different elements of a std::vector
without a lock? (not modifying the vector itself!)
2) Are there easy ways or conventions or patterns to follow to cut a for loop and dispatch to threads?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
1) 是
2) 您可以使用 OpenMP 并行化向量处理。如果您使用 Microsoft VC++ 2010,并发库具有parallel_for 和parallel_for_each 算法。
1) Yes
2) You can use OpenMP to paralellize vector handling. If you are working with Microsoft VC++ 2010, Concurrency library has parallel_for and parallel_for_each algorithms.
对于 1,请参阅我的答案此处:
显然这是 C++11(因为 C++98/03 没有提到线程),但是大多数实现已经符合。
恐怕我不知道任何约定。 OpenMP 或许可以实现自动化。
要手动执行此操作,我可能会使用类似队列的系统,因为并非所有对象都可能需要相同的时间,如果您分成“相等”的部分,则可以让一个线程在其他线程之后完成,而队列则为线程提供数据将通过最大化并行性直到最后来缓解这个问题。
For 1, see my answer here:
Obviously this is C++11 (as C++98/03 made no mention of threads), however most implementations already comply.
I am afraid I don't know any convention. OpenMP could probably automate this.
To do it manually, I would probably use a queue-like system, as not all objects may require the same time, you could have one thread finish well after the others if you split in "equal" portions, whereas a queue feeding the threads would alleviate this issue by maximizing the parallelism up until the very end.
如果您使用的是 VS 2010,则可以使用 并行模式 库来实现多线程。
If you are using VS 2010 you can use the Parallel Patterns library to achieve the multi-threading.
如果您使用的是 g++,则可以使用 gnu 并行模式 http://gcc.gnu .org/onlinedocs/libstdc++/manual/parallel_mode.html
使用标准 stl 算法与自动并行化的 lambda 算法相结合。
If you are using g++, you can use gnu parallel mode http://gcc.gnu.org/onlinedocs/libstdc++/manual/parallel_mode.html
using the standard stl algorithms in combination with lambda's which are auto parallelized.