Parallel processing and further use of output

Russel Winder via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Sep 28 04:28:32 PDT 2015


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:russel.winder at ekiga.net
41 Buckmaster Road    m: +44 7770 465 077   xmpp: russel at winder.org.uk
London SW11 1EN, UK   w: www.russel.org.uk  skype: russel_winder

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 181 bytes
Desc: This is a digitally signed message part
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20150928/8824897e/attachment.sig>


More information about the Digitalmars-d-learn mailing list