Guest User

Untitled

a guest
May 28th, 2018
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.12 KB | None | 0 0
  1. import asyncio
  2. import random
  3.  
  4.  
  5. async def produce(queue, n):
  6. for x in range(n):
  7. # produce an item
  8. print('producing {}/{}'.format(x, n))
  9. # simulate i/o operation using sleep
  10. await asyncio.sleep(random.random())
  11. item = str(x)
  12. # put the item in the queue
  13. await queue.put(item)
  14.  
  15.  
  16. async def consume(queue):
  17. while True:
  18. # wait for an item from the producer
  19. item = await queue.get()
  20.  
  21. # process the item
  22. print('consuming {}...'.format(item))
  23. # simulate i/o operation using sleep
  24. await asyncio.sleep(random.random())
  25.  
  26. # Notify the queue that the item has been processed
  27. queue.task_done()
  28.  
  29.  
  30. async def run(n):
  31. queue = asyncio.Queue()
  32. # schedule the consumer
  33. consumer = asyncio.ensure_future(consume(queue))
  34. # run the producer and wait for completion
  35. await produce(queue, n)
  36. # wait until the consumer has processed all items
  37. await queue.join()
  38. # the consumer is still awaiting for an item, cancel it
  39. consumer.cancel()
  40.  
  41.  
  42. loop = asyncio.get_event_loop()
  43. loop.run_until_complete(run(10))
  44. loop.close()
Add Comment
Please, Sign In to add comment