我认为asyncio.Queue
更适合这种生产者/消费者关系:
import asyncio
import sys
queue = asyncio.Queue()
def handle_stdin():
data = sys.stdin.readline()
# Queue.put is a coroutine, so you can't call it directly.
asyncio.async(queue.put(data))
# Alternatively, Queue.put_Nowait() is not a coroutine, so it can be called directly.
# queue.put_Nowait(data)
async def tick():
while 1:
data = await queue.get()
print('Data received: {}'.format(data))
def main():
loop = asyncio.get_event_loop()
loop.add_reader(sys.stdin, handle_stdin)
loop.run_until_complete(tick())
if __name__ == '__main__':
main()
与相比,所需的逻辑更少Event
,您需要确保正确设置/取消设置,并且无需sleep
像全局变量那样进行唤醒,检查,返回睡眠,循环等操作。因此,该Queue
方法比其他可能的解决方案更简单,更小,并且对事件循环的阻塞更少。其他解决方案在技术上是正确的 ,因为它们可以正常运行(只要您yield from
在ifif event.is_set()
和if data is not None:
block内不引入任何调用)。他们只是笨拙。