我的專案要求我運行一個阻塞代碼(來自另一個庫),同時繼續我的 asyncio while: true 回圈。代碼看起來像這樣:
async def main():
while True:
session_timeout = aiohttp.ClientTimeout()
async with aiohttp.ClientSession() as session:
// Do async stuffs like session.get and so on
# At a certain point, I have a blocking code that I need to execute
// Blocking_code() starts here. The blocking code needs time to get the return value.
Running blocking_code() is the last thing to do in my main() function.
# My objective is to run the blocking code separately.
# Such that whilst the blocking_code() runs, I would like my loop to start from the beginning again,
# and not having to wait until blocking_code() completes and returns.
# In other words, go back to the top of the while loop.
# Separately, the blocking_code() will continue to run independently, which would eventually complete
# and returns. When it returns, nothing in main() will need the return value. Rather the returned
# result continue to be used in blocking_code()
asyncio.run(main())
我試過使用pool = ThreadPool(processes=1)and thread = pool.apply_async(blocking_code, params)。如果在 main() 中的blocking_code() 之后需要做一些事情,這有點作業 但是blocking_code()是main()中的最后一件事,它會導致整個while回圈暫停,直到blocking_code()完成,然后再從頂部開始。
我不知道這是否可能,如果可能,它是如何完成的;但理想的情況是這樣的。
運行 main(),然后在它自己的實體中運行 blocking_code()。就像執行另一個 .py 檔案一樣。因此,一旦回圈到達 main() 中的 blocking_code(),它就會觸發 blocking_code.py 檔案,并且在 blocking_code.py 腳本運行時,while 回圈會再次從頂部繼續。
如果在while回圈的第二次通過時,它再次到達blocking_code()并且之前的運行還沒有完成;另一個blocking_code() 實體將在它自己的實體上獨立運行。
我說的有道理嗎?是否有可能達到預期的結果?
謝謝!
uj5u.com熱心網友回復:
這可以通過執行緒實作。所以你不會阻塞你的主回圈,你需要將你的執行緒包裝在一個 asyncio 任務中。如果需要,您可以在回圈完成后等待回傳值。您可以結合使用asyncio.create_task和asyncio.to_thread
import aiohttp
import asyncio
import time
def blocking_code():
print('Starting blocking code.')
time.sleep(5)
print('Finished blocking code.')
async def main():
blocking_code_tasks = []
while True:
session_timeout = aiohttp.ClientTimeout()
async with aiohttp.ClientSession() as session:
print('Executing GET.')
result = await session.get('https://www.example.com')
blocking_code_task = asyncio.create_task(asyncio.to_thread(blocking_code))
blocking_code_tasks.append(blocking_code_task)
#do something with blocking_code_tasks, wait for them to finish, extract errors, etc.
asyncio.run(main())
上面的代碼在執行緒中運行阻塞代碼,然后將其放入異步任務中。然后我們將其添加到blocking_code_tasks串列中以跟蹤所有當前正在運行的任務。稍后,您可以使用類似的方法獲取值或錯誤asyncio.gather
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/447428.html
上一篇:Prologue-Webframework-使用`--threads:on`標志編譯時如何設定執行緒區域變數進行日志記錄?
