Advertisement
Guest User

Untitled

a guest
Sep 19th, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. import trio
  2. import contextvars
  3.  
  4. LAST_TASK_ID = 0
  5. TASK_ID: contextvars.ContextVar[str] = contextvars.ContextVar("task_id")
  6.  
  7.  
  8. async def producer(num_items: int, send_channel: trio.MemorySendChannel) -> None:
  9. task_id = TASK_ID.get()
  10. iden = f"Producer {task_id}"
  11. print(f"{iden} - Started")
  12. async with send_channel:
  13. for k in range(num_items):
  14. await send_channel.send({"task_id": task_id, "message": f"Message {k}"})
  15. await trio.sleep(0.3)
  16. print(f"{iden} - Done")
  17.  
  18.  
  19. async def consumer(receive_channel: trio.MemoryReceiveChannel) -> None:
  20. task_id = TASK_ID.get()
  21. iden = f"Consumer #{task_id}"
  22. print(f"Starting {iden}")
  23. async for event in receive_channel:
  24. assert event["task_id"] == task_id
  25. message = event["message"]
  26. print(f"{iden} - Received: {message!r}")
  27. result = await process(message)
  28. print(f"{iden} - Result: {result!r}")
  29. print(f"{iden} - Done")
  30.  
  31.  
  32. async def process(message: str) -> str:
  33. task_id = TASK_ID.get()
  34. print(f"Processor {task_id} - Processing message")
  35. return message[::-1]
  36.  
  37.  
  38. async def job(nursery):
  39. # Set up the task_id for the current job.
  40. global LAST_TASK_ID
  41. task_id = LAST_TASK_ID + 1
  42. LAST_TASK_ID = task_id
  43. TASK_ID.set(task_id)
  44.  
  45. # Start other concurrent tasks.
  46. send_channel, receive_channel = trio.open_memory_channel(0)
  47. nursery.start_soon(producer, 10, send_channel)
  48. nursery.start_soon(consumer, receive_channel)
  49.  
  50.  
  51. async def main():
  52. async with trio.open_nursery() as nursery:
  53. for _ in range(3):
  54. nursery.start_soon(job, nursery)
  55. await trio.sleep(1)
  56.  
  57.  
  58. trio.run(main)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement