import asyncio
import time
def blocking_function():
print("Blocking function called")
time.sleep(5)
print("Blocking function finished")
async def concurrent_function():
for x in range(10):
print(x)
await asyncio.sleep(1)
async def main():
print("Main function called")
loop = asyncio.get_event_loop()
loop.run_in_executor(None, blocking_function)
await concurrent_function()
print("Main function finished")
if __name__ == "__main__":
asyncio.run(main())
當 asyncio 代碼也在運行時嘗試運行阻塞函式時,這非常有效。但是,如果我有一個包含阻塞代碼的函式(例如,一個非異步的庫,我無法執行此操作),因為該函式同時包含阻塞代碼和異步代碼,我無法使用run in executor. 我怎樣才能解決這個問題?
由于blocking_function未等待,以下代碼不幸出現錯誤,但您不能將其與run_in_executor
async def blocking_function():
for x in range(4):
print("Blocking function called")
time.sleep(1)
print("Blocking function finished")
print("Async code running:")
await asyncio.sleep(1)
print("Async code finished")
async def concurrent_function():
for x in range(10):
print(x)
await asyncio.sleep(1)
async def main():
print("Main function called")
loop = asyncio.get_event_loop()
loop.run_in_executor(None, blocking_function)
await concurrent_function()
print("Main function finished")
if __name__ == "__main__":
asyncio.run(main())
uj5u.com熱心網友回復:
只需在第二個執行緒中創建一個事件回圈并在那里運行異步函式。
import asyncio
import time
async def blocking_function():
for x in range(4):
print("Blocking function called")
time.sleep(1)
print("Blocking function finished")
print("Async code running:")
await asyncio.sleep(1)
print("Async code finished")
def async_blocking_function_runner(func):
# creates another event loop in the other thread and runs func in it
res = asyncio.run(func())
return res
async def concurrent_function():
for x in range(10):
print(x)
await asyncio.sleep(1)
async def main():
print("Main function called")
loop = asyncio.get_event_loop()
res = loop.run_in_executor(None, async_blocking_function_runner, blocking_function)
await concurrent_function()
await res # make sure the task in second thread is done
print("Main function finished")
if __name__ == "__main__":
asyncio.run(main())
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/531049.html
標籤:Python异步蟒蛇异步
上一篇:以編程方式滾動圖表
