Skip to content

Instantly share code, notes, and snippets.

@camisetags
Created May 23, 2018 14:42
Show Gist options
  • Save camisetags/b326eca67c0369bdda7a57d41cc20bc4 to your computer and use it in GitHub Desktop.
Save camisetags/b326eca67c0369bdda7a57d41cc20bc4 to your computer and use it in GitHub Desktop.
producer-consumer-asyncio
import asyncio
import random
async def produce(queue, n):
for x in range(n):
# produce an item
print('producing {}/{}'.format(x, n))
# simulate i/o operation using sleep
await asyncio.sleep(random.random())
item = str(x)
# put the item in the queue
await queue.put(item)
async def consume(queue):
while True:
# wait for an item from the producer
item = await queue.get()
# process the item
print('consuming {}...'.format(item))
# simulate i/o operation using sleep
await asyncio.sleep(random.random())
# Notify the queue that the item has been processed
queue.task_done()
async def run(n):
queue = asyncio.Queue()
# schedule the consumer
consumer = asyncio.ensure_future(consume(queue))
# run the producer and wait for completion
await produce(queue, n)
# wait until the consumer has processed all items
await queue.join()
# the consumer is still awaiting for an item, cancel it
consumer.cancel()
loop = asyncio.get_event_loop()
loop.run_until_complete(run(10))
loop.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment