How to call stop from parallel foreach

Bastiaan Veelo Bastiaan at Veelo.net
Thu Jun 24 20:33:00 UTC 2021


On Thursday, 24 June 2021 at 18:23:01 UTC, seany wrote:
> I have seen 
> [this](https://forum.dlang.org/thread/akhbvvjgeaspmjntznyk@forum.dlang.org).
>
> I can't call break form parallel foreach.
>
> Okey, Is there a way to easily call .stop() from such a  case?

Yes there is, but it won’t break the `foreach`:
```d
auto tp = taskPool;
foreach (i, ref e; tp.parallel(a))
{
     // …
     tp.stop;
}
```
The reason this does not work is because `stop` terminates the 
worker threads as soon as they are finished with their current 
`Task`, but no sooner. `parallel` creates the `Task`s before it 
presents a range to `foreach`, so no new `Task`s are created 
during iteration. Therefore all elements are iterated.

>     outer: foreach(i, a; parallel(array_of_a)) {
>        foreach(j, b; parallel(array_of_b)) {

By the way, nesting parallel `foreach` does not make much sense, 
as one level already distributes the load across all cores (but 
one). Additional parallelisation will likely just add overhead, 
and have a net negative effect.

— Bastiaan.




More information about the Digitalmars-d-learn mailing list