【发布时间】: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