Python 异步协程和生成器位于一个对象中

问题描述 投票:0回答:1

是否有可能有两个协程,一个在异步生成器上迭代,另一个等待迭代停止?喜欢

coro1(gen):
    async for _ in gen:
        await asyncio.sleep(1)

coro2(gen):
    await gen
    print('generation finished')
python python-asyncio generator
1个回答
0
投票

没有自动通知,但您可以让 coro1 通过

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())
© www.soinside.com 2019 - 2024. All rights reserved.