繁体   English   中英

Python asyncio 等待并通知

[英]Python asyncio wait and notify

我正在尝试做类似 C# ManualResetEvent 但在 Python 中的事情。

我试图在 python 中这样做,但似乎没有用。

import asyncio

cond = asyncio.Condition()

async def main():
    some_method()

    cond.notify()

async def some_method():
    print("Starting...")
    
    await cond.acquire()
    await cond.wait()
    cond.release()
    
    print("Finshed...")

main()

我希望 some_method 启动然后等到有信号重新启动。

这段代码不完整,首先你需要使用asyncio.run()来引导事件循环——这就是你的代码根本没有运行的原因。

其次, some_method()从未真正开始。 您需要使用asyncio.create_task()异步启动some_method() ) 。 当你调用“ async def函数”(更正确的术语是 coroutinefunction)时,它返回一个协程 object,这个 object 需要由事件循环驱动,要么通过await它,要么使用前面提到的 ZC1C4252674E68384F1457A。

您的代码应该看起来更像这样:

import asyncio

async def main():
    cond = asyncio.Condition()

    t = asyncio.create_task(some_method(cond))

    # The event loop hasn't had any time to start the task
    # until you await again. Sleeping for 0 seconds will let
    # the event loop start the task before continuing.
    await asyncio.sleep(0)
    cond.notify()

    # You should never really "fire and forget" tasks,
    # the same way you never do with threading. Wait for
    # it to complete before returning:
    await t

async def some_method(cond):
    print("Starting...")
    
    await cond.acquire()
    await cond.wait()
    cond.release()
    
    print("Finshed...")

asyncio.run(main())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM