asyncio異步 loop.run_in_executor操作同步方法變成異步操作


import time
import asyncio
from concurrent.futures import ThreadPoolExecutor


def long_blocking_function():
    print(time.time())
    time.sleep(2)
    return True


async def run():
    loop = asyncio.get_event_loop()
    # 新建線程池
    pool = ThreadPoolExecutor()
    # 任務列表
    tasks = [loop.run_in_executor(pool, long_blocking_function),
             loop.run_in_executor(pool, long_blocking_function)]
    # 等待所有任務結束並返回
    return await asyncio.gather(*tasks)



if __name__ == '__main__':
    # 獲取新的事件循環
    loop = asyncio.new_event_loop()
    # 設置當前事件循環
    asyncio.set_event_loop(loop)
    now = time.time()
    loop.run_until_complete(run())
    print(time.time() - now)

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM