On Sat, 2015-09-26 at 12:32 +0000, Zoidberg via Digitalmars-d-learn
wrote:
> > 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;
> > }
> 
> Thanks! Works fine. So "shared" and "atomic" is a must?

Yes and no. But mostly no. If you have to do this as an explicit
iteration (very 1970s) then yes to avoid doing things wrong you have to
ensure the update to the shared mutable state is atomic.

A more modern (1930s/1950s) way of doing things is to use implicit
iteration – something Java, C++, etc. are all getting into more and
more, you should use a reduce call. People have previously mentioned:

    taskPool.reduce!"a + b"(iota(1UL,1000001))

which I would suggest has to be seen as the best way of writing this
algorithm.

 
-- 
Russel.
=============================================================================
Dr Russel Winder      t: +44 20 7585 2200   voip: sip:[email protected]
41 Buckmaster Road    m: +44 7770 465 077   xmpp: [email protected]
London SW11 1EN, UK   w: www.russel.org.uk  skype: russel_winder

Attachment: signature.asc
Description: This is a digitally signed message part

Reply via email to