【问题标题】:How to await a coroutine until a condition is met?如何等待协程直到满足条件?
【发布时间】:2019-12-29 23:51:22
【问题描述】:

我是 Python 异步编程的新手,我正在尝试编写一个示例协程,该协程一直等待,直到满足任意条件。这是实现它的正确方法吗?

async def foo():
    print('foo')   # this is executed before we start checking the condition
    while not condition:
        await asyncio.sleep(1)
    print('bar')   # this is executed after the condition is met

【问题讨论】:

  • 正确的做法是使用Events

标签: python python-3.x async-await python-asyncio


【解决方案1】:

正如@L3viathan 提到的,asyncio.Event 可以用来实现它。

这是一个小例子:

import asyncio


async def foo(event):
    while True:
        print('foo')
        await event.wait()
        print('bar')


async def main():
    event = asyncio.Event()

    asyncio.create_task(foo(event))

    for i in range(5):
        await asyncio.sleep(i)
        event.set()
        event.clear()


asyncio.run(main())

【讨论】:

    猜你喜欢
    • 2018-01-27
    • 2012-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-17
    • 1970-01-01
    • 2015-07-28
    相关资源
    最近更新 更多