【问题标题】:Equivalent to "yield" in Python's "async def" functions相当于 Python 的“async def”函数中的“yield”
【发布时间】:2018-08-23 18:20:16
【问题描述】:

我听说@asyncio.coroutine 版本的协程最终将在 Python 中被弃用(可能在 3.8 之后?),并且仅支持 async def。今天我使用装饰器版本以便能够只使用yield(而不是yield from另一个协程),因为我正在等待一些更改(在内部进行轮询,例如while循环)或拆分大部分将耗时的代码阻塞成更小的块(从而改善并发体验)。

这是一个最小的例子:

import asyncio

@asyncio.coroutine
def foo(l):
    print('entering foo')
    while l[0] == 0:
        yield
    print('leaving foo')

async def bar(l):
    print('entering bar')
    await asyncio.sleep(1)
    l[0] = 1
    await asyncio.sleep(1)
    print('leaving bar')

async def main():
    l = [0]
    t0 = asyncio.ensure_future(foo(l))
    t1 = asyncio.ensure_future(bar(l))
    await t0
    await t1

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

这将打印以下内容:

entering foo
entering bar
# foo is polling
# 1 second elapses
leaving foo
# 1 second elapses
leaving bar

我们如何在async def 版本的协程中实现这一点?我们应该使用await asyncio.sleep(0)吗?

【问题讨论】:

    标签: python-asyncio


    【解决方案1】:

    await asyncio.sleep(0) 可以用来做你想做的事,但在目前的情况下,这不是一个好的解决方案。事件循环需要返回到foo 执行的每个“滴答”:它浪费了 CPU 资源。

    当你想在协程中等待某些事情发生时,正确的方法是使用asyncio.Event:

    async def foo(event):
        print('entering foo')
        await event.wait()
        print('leaving foo')
    
    async def bar(event):
        print('entering bar')
        await asyncio.sleep(1)
        event.set()
        await asyncio.sleep(1)
        print('leaving bar')
    
    async def main():
        event = asyncio.Event()
        t0 = asyncio.ensure_future(foo(event))
        t1 = asyncio.ensure_future(bar(event))
        await t0
        await t1
    
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
    

    这种方式事件循环只会返回到foo一次:当event实际上已经被设置时。

    【讨论】:

    • 谢谢@Mikhail,我不知道发生了什么事。
    • 为此目的甚至可以使用Future。它比Event 更轻量级,并且可以携带有效载荷 - 等待侧的some_obj = await future 和发送侧的future.set_result(some_obj)。 asyncio 本身在很多地方都使用了这种技术。
    • 确实更灵活。谢谢@user4815162342。
    【解决方案2】:

    是的,我认为await asyncio.sleep(0) 是正确的做法,请参阅https://github.com/python/asyncio/issues/284。所以foo变成了:

    async def foo(l):
        print('entering foo')
        while l[0] == 0:
            await asyncio.sleep(0)
        print('leaving foo')
    

    【讨论】:

    • 赞成(除了接受的答案),因为这正确回答了所提出的问题,并提供了有用的参考。很遗憾这个isn't documented。
    • 谢谢@user4815162342。
    猜你喜欢
    • 2021-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-04
    • 2017-08-21
    • 1970-01-01
    • 1970-01-01
    • 2017-05-06
    相关资源
    最近更新 更多