Advertisement
Pandaaaa906

Untitled

Mar 4th, 2024
734
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.85 KB | None | 0 0
  1. import asyncio
  2. from asyncio import Queue
  3.  
  4. from loguru import logger
  5.  
  6.  
  7. async def processor_1(q1: Queue):
  8.     while True:
  9.         item = await q1.get()
  10.         logger.info(f"processor_1: processing {item}")
  11.         q1.task_done()
  12.  
  13.  
  14. async def processor_2(q2: Queue):
  15.     while True:
  16.         item = await q2.get()
  17.         logger.info(f"processor_2: processing {item}")
  18.         q2.task_done()
  19.  
  20.  
  21. async def producer(q1, q2):
  22.     for i in range(10):
  23.         await q1.put(i)
  24.         await q2.put(i * 2)
  25.  
  26.  
  27. async def main():
  28.     q1 = Queue()
  29.     q2 = Queue()
  30.     tasks = [
  31.         asyncio.create_task(processor_1(q1)),
  32.         asyncio.create_task(processor_2(q2)),
  33.     ]
  34.  
  35.     await producer(q1, q2)
  36.    
  37.     await q1.join()
  38.     await q2.join()
  39.     for t in tasks:
  40.         t.cancel()
  41.  
  42.  
  43. if __name__ == '__main__':
  44.     asyncio.run(main())
  45.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement