Multithreaded worker application
Save as workers.atom. A producer and a consumer share a bounded channel. They can run concurrently even while the caller waits. The program also distributes independent calculations with task.parallel.
Start a producer and a consumer
Both workers share a channel with room for two messages at a time. The caller waits for the consumer’s sum, which is 15.
queue = task.channel(2)
producer = task.spawn(produce, queue, 6)
consumer = task.spawn(consume, queue)
try:
assert(task.wait(consumer, 4) == 15)
task.wait(producer, 4)
Show full source 34 lines
use task
func produce(queue, limit):
try:
for n in 1..limit:
task.send(queue, n, 3)
finally:
task.close(queue)
func consume(queue):
total = 0
while true:
message = task.receive(queue, 3)
if not message.open:
break
total += message.value
return total
func square(value):
return value * value
queue = task.channel(2)
producer = task.spawn(produce, queue, 6)
consumer = task.spawn(consume, queue)
try:
assert(task.wait(consumer, 4) == 15)
task.wait(producer, 4)
results = task.parallel([2, 3, 4], square, 2)
assert(results[2] == 16)
print('Consumed sequence, then computed squares.')
finally:
task.close(queue)
task.cancel(producer)
task.cancel(consumer)