Path: blob/master/languages/python/asyncio_examples/producer.py
1240 views
import asyncio1import random23async def produce(queue, n):4for x in range(1, n+1):5# produce an item6print(('producing {}/{}'.format(x, n)))7# simulate i/o operation using sleep8await asyncio.sleep(random.random())9item = str(x)10# put the item in the queue11await queue.put(item)121314async def consume(queue):15while True:16# wait for an item from the producer17item = await queue.get()18if item is None:19# producer emits None to indicate that it is done20break2122# process the item2324print(("consuming item {}...".format(item)))25# simulate the i/o operation using sleep26await asyncio.sleep(random.random())2728loop = asyncio.get_event_loop()29queue = asyncio.Queue(loop=loop)30producer_coro = produce(queue, 10)31consumer_coro = consume(queue)3233loop.run_until_complete(asyncio.gather(producer_coro, consumer_coro))34loop.close()353637