Parallel For

jfondren julian.fondren at gmail.com
Tue Jun 15 07:41:06 UTC 2021


On Tuesday, 15 June 2021 at 06:39:24 UTC, seany wrote:
> What am I doing wrong?

add a `writeln(c.length);` in your inner loop and consider
the output. If you were always pushing to the end of c, then
only unique numbers should be output. But I see e.g. six
occurrences of 0, four of 8 ...

Here's a non-solution:

```d
import std;
import core.sync.mutex;

void main() {
     int[] a = [1, 2, 3, 4, 5, 6, 7, 8, 9];
     int[] b = [11, 12, 13, 14, 15, 16, 17, 18];
     int[] c;
     shared Mutex mtx = new shared Mutex();
     foreach (aa; parallel(a)) {
         foreach (bb; parallel(b)) {
             mtx.lock_nothrow();
             c ~= aa + bb;
             mtx.unlock_nothrow();
         }
     }
     writeln(c);
}
```

That solves the inconsistent access to c, but the parallelism
is probably pointless.

Real solutions might include

1. `c[i] = aa + bb;`, with a calculated unique i per assignment.

2. std.concurrency and message passing to build c?

3. using core.atomic for i?



More information about the Digitalmars-d-learn mailing list