Path: blob/master/languages/python/asyncio_examples/producer_consumer_task_done.py
1240 views
"""1A simple producer/consumer example using Queue.task_done and Queue.join2"""34import asyncio5import random67async def produce(queue, n):8for x in range(n):9# produce an item10print(('producing {}/{}'.format(x, n)))11# simulate i/o operation using sleep12await asyncio.sleep(random.random())13item = str(x)14# put the item in the queue15await queue.put(item)161718async def consume(queue):19while True:20# wait for an item from the producer21item = await queue.get()2223# process the item24print(("consuming {}...".format(item)))25# simulate i/o operation using sleep26await asyncio.sleep(random.random())2728# notify the queue that the item has been processed.29queue.task_done()3031async def run(n):32queue = asyncio.Queue()33# schedule a consumer34consumer = asyncio.ensure_future(consume(queue))35# run the producer and wait for completion36await produce(queue, n)37# wait until the consumer has processed all items38await queue.join()39# the consumer is still awaiting for an item, cancel it40consumer.cancel()4142loop = asyncio.get_event_loop()43loop.run_until_complete(run(10))44loop.close()454647