Reputation: 187
I am reading C++17 in detail. There is a description for std::for_each below, in this book:
In the serial version of for_each, the version that was available before C++17 >you get a unary function 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.
I still understand, why parallel std::for_each can not return the functor f. Although the order of invocations is indeterminate, parallel for_each block to wait invoke finish.When every parallel operation finish, returning the f is seemed ok.
Upvotes: 1
Views: 220
Reputation: 238341
The idea behind returning the functor is to allow the functor to accumulate state across successive calls. The accumulated state could be accessed through the returned copy.
Accumulation requires serial access to the accumulated state, which would defeat the purpose of parallel execution. Essentially, each thread of execution will get a copy of the function object and their state is not shared.
The standard has following note:
[Note: Does not return a copy of its Function parameter, since parallelization may not permit efficient state accumulation. — end note]
Upvotes: 6