Parallel processing and further use of output
John Colvin via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Sep 26 05:29:37 PDT 2015
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;
}
More information about the Digitalmars-d-learn
mailing list