Jump to content

Atomic updates: Difference between revisions

Added Mathematica
(Added another example)
(Added Mathematica)
Line 2,481:
true.
</lang>
 
=={{header|Mathematica}}==
<lang Mathematica>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]]}];</lang>
{{out}}
<pre>Original sum: &lt;number&gt;
Current sum: &lt;same number, stays fixed&gt;</pre>
This simply uses a variable named <tt>comp</tt> to determine whether or not it is currently computing something.
 
=={{header|Oz}}==
Cookies help us deliver our services. By using our services, you agree to our use of cookies.