1# program for broadcasting messages over channel; see 2# http://pycos.sourceforge.io/tutorial.html for details. 3 4import random 5import pycos 6 7 8def seqsum(task=None): 9 # compute sum of numbers received (from channel) 10 result = 0 11 while True: 12 msg = yield task.receive() 13 if msg is None: 14 break 15 result += msg 16 print('sum: %f' % result) 17 18 19def seqprod(task=None): 20 # compute product of numbers received (from channel) 21 result = 1 22 while True: 23 msg = yield task.receive() 24 if msg is None: 25 break 26 result *= msg 27 print('prod: %f' % result) 28 29 30def client_proc(task=None): 31 # create channel 32 channel = pycos.Channel('sum_prod') 33 # create tasks to compute sum and product of numbers sent 34 sum_task = pycos.Task(seqsum) 35 prod_task = pycos.Task(seqprod) 36 # subscribe tasks to channel so they receive messages 37 yield channel.subscribe(sum_task) 38 yield channel.subscribe(prod_task) 39 # send 4 numbers to channel 40 for _ in range(4): 41 r = random.uniform(0.5, 3) 42 channel.send(r) 43 print('sent %f' % r) 44 # send None to indicate end of data 45 channel.send(None) 46 yield channel.unsubscribe(sum_task) 47 yield channel.unsubscribe(prod_task) 48 49 50if __name__ == '__main__': 51 # create pycos Task 52 pycos.Task(client_proc) 53