How to break from parallel foreach?

Russel Winder russel at winder.org.uk
Wed Feb 27 07:31:32 UTC 2019


On Tue, 2019-02-26 at 21:36 +0000, Jordan Wilson via Digitalmars-d-learn
wrote:
> On Tuesday, 26 February 2019 at 19:58:24 UTC, Andrey wrote:
> > Hello,
> > How to break from parallel foreach?
> > More general question - how to control such loop?
> 
> A basic way would be to use a flag:
> 
> shared stopWork=false;
> foreach (wordBag; wordBags.parallel) {
>      if (!stopWork) {
>          // do work
>          if (wordBag.canFind("myword")) stopWork=true
>      }
> }
> 
> I'd say it's probably not an elegant solution to "break" from 
> parallel forloops, but that's up to you to decide.
> 
> Jordan
> 

Isn't this really an example of exactly how not to use parallel for loops? The
existence of the global data (with respect to the loop body) is surely
attempting to impose (and almost certainly failing) a sequential solution on
what is a parallel computation.

Given the scatter/gather semantics of parallel for loops, each loop body will
evaluate stopWork and act accordingly, i.e. they will all evaluate and the
gather (and possible reduction) happen.

Certainly, because of finite resources, there is an element of sequential
behaviour in a parallel for, but this is implementation detail. Conceptually,
all loop bodies of a parallel for are executed at the same time. 

-- 
Russel.
===========================================
Dr Russel Winder      t: +44 20 7585 2200
41 Buckmaster Road    m: +44 7770 465 077
London SW11 1EN, UK   w: www.russel.org.uk

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


More information about the Digitalmars-d-learn mailing list