RosettaCodeData/Task/Atomic-updates/Mathematica/atomic-updates.math

22 lines
895 B
Plaintext

transfer[bucks_, src_, dest_, n_] :=
ReplacePart[
bucks, {src -> Max[bucks[[src]] - n, 0],
dest -> bucks[[dest]] + Min[bucks[[src]], n]}];
DistributeDefinitions[transfer];
SetSharedVariable[bucks, comp];
bucks = RandomInteger[10, 20];
comp = True;
Print["Original sum: " <> IntegerString[Plus @@ bucks]];
Print[Dynamic["Current sum: " <> IntegerString[Plus @@ bucks]]];
WaitAll[{ParallelSubmit[
While[True, While[! comp, Null]; comp = False;
Module[{a = RandomInteger[{1, 20}], b = RandomInteger[{1, 20}]},
bucks = transfer[bucks, Max[a, b], Min[a, b],
Floor[Abs[bucks[[a]] - bucks[[b]]]/2]]]; comp = True]],
ParallelSubmit[
While[True, While[! comp, Null]; comp = False;
Module[{src = RandomInteger[{1, 20}],
dest = RandomInteger[{1, 20}]},
bucks = transfer[bucks, src, dest,
RandomInteger[{1, bucks[[src]]}]]]; comp = True]]}];