How do I break from loop when using parallel()?
Neia Neutuladh
neia at ikeran.org
Mon May 28 22:52:41 UTC 2018
On Monday, 28 May 2018 at 21:04:21 UTC, Dr.No wrote:
> import std.parallelism : parallel;
> foreach(t; parallel(arr))
> {
> if(!doSomething(t)) {
> return false;
> }
> }
>
> It reuturns the run time error:
>
>> std.parallelism.ParallelForeachError@(0): Cannot break from a
>> parallel foreach loop using break, return, labeled
>> break/continue or goto statements.
>
> What's the proper way to break from loop?
By the time you try to break out of the loop, you've already
executed the loop body for later elements in the collection. So
if you could do that, it would give the wrong impression.
The loop body executes on several threads at once. The `return
false` statement might be executing on a different thread, and
`return` only returns on the same thread.
If you want to do this sort of thing (exit on first error, for
instance), you can manually use TaskPool, schedule tasks on it,
and use an atomic variable to exit early on each task if
necessary.
More information about the Digitalmars-d-learn
mailing list