On Saturday, 26 September 2015 at 12:18:16 UTC, Zoidberg wrote:
I've run into an issue, which I guess could be resolved easily, if I knew how...

[CODE]
    ulong i = 0;
    foreach (f; parallel(iota(1, 1000000+1)))
    {
        i += f;
    }
    thread_joinAll();
    i.writeln;
[/CODE]

It's basically an example which adds all the numbers from 1 to 1000000 and should therefore give 500000500000. Running the above code gives 205579930677, leaving out "thread_joinAll()" the output is 210161213519.

I suspect there's some sort of data race. Any hint how to get this straight?

Here's a correct version:

import std.parallelism, std.range, std.stdio, core.atomic;
void main()
{
    shared ulong i = 0;
    foreach (f; parallel(iota(1, 1000000+1)))
    {
        i.atomicOp!"+="(f);
    }
    i.writeln;
}

Reply via email to