Checkpoint synchronization: Difference between revisions

(→‎{{header|Tcl}}: Added zkl)
Line 2,231:
B is ready
D is ready
</pre>
 
=={{header|zkl}}==
Simulate a pool of workers, each making one part, waiting for the part to be requested and then putting the part on a conveyor belt to be sent to the station that assembles all parts into a product. After shipping the part, it turns off the request flag.
The consumer requests a part it doesn't have, waits for a part and puts the received part (which might not be the requested one (if buggy code)) in a bin and assembles the parts into a product.
Repeat until all requested products are made.
<lang zkl>const NUM_PARTS=5; // number of parts used to make the product
var requested=Atomic.Int(-1); // the id of the part the consumer needs
var pipe=Thread.Pipe(); // "conveyor belt" of parts to consumer
 
fcn producer(id,pipe){
while(True){ // make part forever
requested.waitFor(id); // wait for consumer to ask for my part
requested.set(-1); // I'm making the part
pipe.write(id); // ship my part
}
println(id," stopped");
}
 
foreach id in (NUM_PARTS){ producer.launch(id,pipe) } // start workers/threads
 
do(10){ // make 10 products
product:=NUM_PARTS.pump(List(),False); // parts I have
while(False!=(id:=product.filter1n('!=(True)))){ // gather parts to make product
requested.set(id);
part:=pipe.read(); // get requested part
product[part]=True; // assemble part into a product
}
println("product made: ",product);
product.clear(); // no parts
}
println("Done"); // but workers are still waiting</lang>
An AtomicInt is an integer that does its operations in an atomic fashion. It is used to serialize the producers and consumer.
 
The filter1n list method returns the index of the first list element that meets the filter test else False.
{{out}}
<pre>
product made: L(True,True,True,True,True)
product made: L(True,True,True,True,True)
product made: L(True,True,True,True,True)
product made: L(True,True,True,True,True)
product made: L(True,True,True,True,True)
product made: L(True,True,True,True,True)
product made: L(True,True,True,True,True)
product made: L(True,True,True,True,True)
product made: L(True,True,True,True,True)
product made: L(True,True,True,True,True)
Done
</pre>
 
Anonymous user