gpt4 book ai didi

c++ - 为什么并行 std::for_each 返回 void

转载 作者:太空宇宙 更新时间:2023-11-04 15:30:31 26 4
gpt4 key购买 nike

我正在阅读 C++17 in detail .std::for_each 的描述如下,在这本书中:

In the serial version of for_each, the version that was available before C++17 >you get a unaryfunction as a return value from the algorithm.Returning such an object is not possible in a parallel version, as the order >of invocations is indeterminate.

我还是明白了,为什么并行std::for_each不能返回仿函数f。虽然调用顺序不确定,但并行 for_each block 等待调用完成。当每个并行操作完成时,返回 f 似乎没问题。

最佳答案

返回仿函数背后的想法是允许仿函数在连续调用中累积状态。可以通过返回的拷贝访问累积的状态。

累加需要对累加状态进行串行访问,这会破坏并行执行的目的。本质上,每个执行线程都将获得函数对象的拷贝,并且它们的状态是不共享的。

标准有如下注释:

[Note: Does not return a copy of its Function parameter, since parallelization may not permit efficient state accumulation. — end note]

关于c++ - 为什么并行 std::for_each 返回 void,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54701946/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com