簡體   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