First time using Parallel

Bastiaan Veelo Bastiaan at Veelo.net
Sun Dec 26 15:20:09 UTC 2021


On Sunday, 26 December 2021 at 06:10:03 UTC, Era Scarecrow wrote:

[...]

> ```d
> foreach(value; taskPool.parallel(range) ){code}
> ```

[...]

>  Now said results are out of order

[...]

>  So I suppose, is there anything I need to know? About shared 
> resources or how to wait until all threads are done?

Have a look at `taskPool.workerLocalStorage`. I learned about 
this in [a post by data 
pulverizer](https://forum.dlang.org/post/ddgxqoitxoaljfwnlogc@forum.dlang.org), who gives this example (slightly modified):
```d
import std.traits : isFloatingPoint;

auto dot(T)(T[] x, T[] y) if (isFloatingPoint!T)
in (y.length == x.length)
{
     import std.range : iota;
     import std.parallelism : parallel, taskPool;

     auto sums = taskPool.workerLocalStorage(0.0L);
     foreach (i; parallel(iota(x.length)))
         sums.get += x[i] * y[i];
     T result = 0.0;
     foreach (threadResult; sums.toRange)
         result += threadResult;
     return result;
}

void main()
{
     double[] x = [1, 2, 3, 4, 5];
     double[] y = [6, 7, 8, 9, 10];
     assert(dot(x, y) == 130);
}
```
(https://run.dlang.io/is/Ia8A0k)

So if you use `workerLocalStorage` to give each thread an 
`appender!string` to write output to, and afterwards write those 
to `stdout`, you'll get your output in order without sorting.

--Bastiaan.



More information about the Digitalmars-d-learn mailing list