RosettaCodeData/Task/Checkpoint-synchronization/Zkl/checkpoint-synchronization.zkl

27 lines
1013 B
Plaintext

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
product:=NUM_PARTS.pump(List(),0); // parts I have on hand
do(10){ // make 10 products
while(False!=(id:=product.filter1n('==(0)))){ // gather parts to make product
requested.set(id);
part:=pipe.read(); // get requested part
product[part]+=1; // assemble part into product
}
println("product made: ",product);
foreach n in (NUM_PARTS){ product[n]-=1 } // remove parts from bin
}
println("Done"); // but workers are still waiting