Atomic updates: Difference between revisions

Added another example
(Added zkl)
(Added another example)
Line 3,413:
L(4,5,4,5,10,5,5,5,3,9)-->55 336642 transfers 20 threads
</pre>
Another solution, using a Pipe as a "holding tank". Pipes are thread safe queues. This code just moves the values to and from the pipe to synchronize changes. The use of this class is the same as above, just change b:=B() to b:=C();
<lang zkl>class C{
const N=10;
var [const]
buckets=(1).pump(N,List).copy(), //(1,2,3...)
pipe = Thread.Pipe(), cnt=Atomic.Int();
fcn init{
pipe.write(buckets);
"Initial sum: ".println(values().sum());
}
fcn transferArb{ // transfer arbitary amount from 1 bucket to another
b1:=(0).random(N); b2:=(0).random(N);
v:=pipe.read();
t:=(0).random(v[b1]); v[b1]=v[b1]-t; v[b2]=v[b2]+t;
pipe.write(v);
cnt.inc();
}
fcn transferEq{ // try to make two buckets equal
b1:=(0).random(N); b2:=(0).random(N);
v:=pipe.read();
v1:=v[b1]; v2:=v[b2]; t:=(v1-v2).abs()/2;
if (v1<v2) t = -t;
v[b1]=v1-t; v[b2]=v2+t;
pipe.write(v);
cnt.inc();
}
fcn values{
v:=pipe.read(); v2:=v.copy(); pipe.write(v);
v2;
}
}</lang>
 
 
Anonymous user