Re: Incorrect parallel computation
- To: mathgroup at smc.vnet.net
 - Subject: [mg125986] Re: Incorrect parallel computation
 - From: Zach Bjornson <bjornson at stanford.edu>
 - Date: Wed, 11 Apr 2012 18:19:26 -0400 (EDT)
 - Delivered-to: l-mathgroup@mail-archive0.wolfram.com
 - References: <jlrhi8$eoe$1@smc.vnet.net>
 
On Apr 8, 1:17 am, Yasha Gindikin <gindi... at gmail.com> wrote:
> Dear colleagues,
>
> would you please advise me on why the following simple code executes incorrectly when parallelized?
>
> a = Subsets[Range[1, 5], {3}];
> L = Length@a;
> b = Table[0, {5}];
> c = Table[0, {5}];
> SetSharedVariable[c];
> Do[b[[a[[l, k]]]] += 1, {l, L}, {k, 3}];
> ParallelDo[c[[a[[l, k]]]] += 1, {l, L}, {k, 3}];
> b===c
>
> False
>
> Thank you!
> Best regards,
> Yasha Gindikin.
If you have a situation where each iteration is slow (e.g. where the
time to access the results variable c is negligible relative to the
time to compute its new value), try CriticalSection as below. In this
simplified example, it will be slower than plain Do because of
locking.
a = Subsets[Range[1, 5], {3}];
L = Length@a;
b = Table[0, {5}];
Do[b[[a[[l, k]]]] += 1, {l, L}, {k, 3}];
c = Table[0, {5}];
SetSharedVariable[c];
ParallelDo[CriticalSection[{clock}, c[[a[[l, k]]]] += 1], {l, L}, {k,
3}]
b===c
True
-Zach