是否有可能有两个协程,一个在异步生成器上迭代,另一个等待迭代停止?喜欢
coro1(gen):
async for _ in gen:
await asyncio.sleep(1)
coro2(gen):
await gen
print('generation finished')
asyncio.Event
: 通知 coro2
import asyncio
async def coro1(gen, event):
async for _ in gen:
await asyncio.sleep(1)
event.set()
async def coro2(event):
await event.wait()
print('generation finished')
async def generator():
yield 1
yield 2
async def main():
event = asyncio.Event()
gen = generator()
await asyncio.gather(coro1(gen, event), coro2(event))
asyncio.run(main())
您还可以将此通知构建到生成器本身中,或将其放入包装器生成器中:
import asyncio
import functools
async def _notification_wrapper(gen, event):
# Unfortunately, async generators don't support yield from.
async for item in gen:
yield item
event.set()
def notification_wrapper(gen):
event = asyncio.Event()
return _notification_wrapper(gen, event), event
async def generator():
yield 1
yield 2
async def coro1(gen):
async for _ in gen:
await asyncio.sleep(1)
async def coro2(event):
await event.wait()
print('generation finished')
async def main():
gen, event = notification_wrapper(generator())
await asyncio.gather(coro1(gen), coro2(event))
asyncio.run(main())