Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import asyncio
- import random
- async def recv(message: str, max_sleep: int):
- sleep_time = max_sleep * random.random()
- await asyncio.sleep(sleep_time)
- return f'{message} awaited for {sleep_time:.2f}s'
- class ConnectionWrapper:
- def __init__(self):
- self.queue = asyncio.Queue()
- async def wrapper1():
- while True:
- msg = await recv("Messager 1", 1)
- await self.queue.put(msg)
- async def wrapper2():
- while True:
- msg = await recv("Messager 2", 2)
- await self.queue.put(msg)
- self.task1 = asyncio.create_task(wrapper1())
- self.task2 = asyncio.create_task(wrapper2())
- async def recv(self):
- return await self.queue.get()
- async def _start():
- connection_wrapper = ConnectionWrapper()
- while True:
- result = await connection_wrapper.recv()
- print(result)
- loop = asyncio.get_event_loop()
- loop.run_until_complete(_start())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement