我目前使用AsyncIO的這段代碼運行得很好。
async defmain():
while(1)。
loop.create_task(startAsyncJob())
await asyncio.sleep(1)
async def startAsyncJob()。
#myCodeHere[/span].
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
我試圖添加一個多執行緒層,這樣我就可以在我的 "main "里面并發地運行多塊內容。所以我提取了它的代碼,把它放在自己的函式AsyncJobThread中,我通過我的新的main函式使用執行緒啟動:
def main()。
try:
_thread.start_new_thread( AsyncJobThread, (1)
_thread.start_new_thread( AsyncJobThread, (15)
except:
print ("Error: unable to start thread"/span>)
async def AsyncJobThread(frequence)。
while(1)。
loop.create_task(startAsyncJob())
await asyncio.sleep(frequence)
async def startAsyncJob()。
#myCodeHere[/span].
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
然而,目前的實作給我帶來了以下錯誤:
sys:1: RuntimeWarning: coroutine 'AsyncJobThread' was never awaited
RuntimeWarning: 啟用tracemalloc以獲得object分配的跟蹤記錄
uj5u.com熱心網友回復:
按照要求,這里是你修改后的代碼,使用了asyncio.gather。
async def main()。
await asyncio.gather(
AsyncJobThread(1)。
AsyncJobThread(15)。
)
async def AsyncJobThread(frequence)。
loop = asyncio.get_event_loop()
while True:
loop.create_task(startAsyncJob())
await asyncio.sleep(frequence)
async def startAsyncJob()。
#myCodeHere
asyncio.run(main())
如果你愿意,你也可以獲得一個對回圈的參考,并將其傳入AsyncJobThread。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/325316.html
標籤:
