[英]How can I run concurrently blocking functions?
我正在創建一個 Python 應用程序,我在其中接收一些數據,我需要處理這些數據。 我無法同步執行此操作,因為我一直在接收數據,所以我需要同時處理數據。
問題是我使用的庫不支持asyncio
,所以我不知道我是否可以同時運行它。 這是我的代碼:
async def event_dispatcher(num):
data = blocking_operation(num)
print(data)
async def main():
tasks = [loop.create_task(event_dispatcher(1)), loop.create_task(event_dispatcher(2)), loop.create_task(event_dispatcher(3)),
loop.create_task(event_dispatcher(4)), loop.create_task(event_dispatcher(5)), loop.create_task(event_dispatcher(6))]
await asyncio.gather(*tasks)
其中blocking_operation
是我不能同時運行的function。 所以基本上我預計tasks
中的 function 會同時運行,但由於blocking_operation
,它們會一次運行一個。 有沒有辦法解決這個問題? 還是我被迫使用另一個庫或多處理?
您可以使用run_in_executor
,它將在后台的線程池中提交阻塞代碼:
async def event_dispatcher(num):
loop = asyncio.get_event_loop()
data = await loop.run_in_executor(None, blocking_operation, num)
print(data)
從 Python 3.9 開始,您還可以使用asyncio.to_thread
:
async def event_dispatcher(num):
data = await asyncio.to_thread(blocking_operation, num)
print(data)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.