您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python异步:阅读器回调和协程通信

Python异步:阅读器回调和协程通信

我认为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内不引入任何调用)。他们只是笨拙。

python 2022/1/1 18:34:09 有416人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶