當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python asyncio.loop.run_in_executor用法及代碼示例


用法:

awaitable loop.run_in_executor(executor, func, *args)

安排在指定的執行程序中調用func

executor 參數應該是一個concurrent.futures.Executor 實例。如果 executorNone ,則使用默認執行程序。

例子:

import asyncio
import concurrent.futures

def blocking_io():
    # File operations (such as logging) can block the
    # event loop: run them in a thread pool.
    with open('/dev/urandom', 'rb') as f:
        return f.read(100)

def cpu_bound():
    # CPU-bound operations will block the event loop:
    # in general it is preferable to run them in a
    # process pool.
    return sum(i * i for i in range(10 ** 7))

async def main():
    loop = asyncio.get_running_loop()

    ## Options:

    # 1. Run in the default loop's executor:
    result = await loop.run_in_executor(
        None, blocking_io)
    print('default thread pool', result)

    # 2. Run in a custom thread pool:
    with concurrent.futures.ThreadPoolExecutor() as pool:
        result = await loop.run_in_executor(
            pool, blocking_io)
        print('custom thread pool', result)

    # 3. Run in a custom process pool:
    with concurrent.futures.ProcessPoolExecutor() as pool:
        result = await loop.run_in_executor(
            pool, cpu_bound)
        print('custom process pool', result)

asyncio.run(main())

此方法返回一個asyncio.Future 對象。

使用 functools.partial() 將關鍵字參數傳遞給 func

在 3.5.3 版中更改:asyncio.loop.run_in_executor不再配置max_workers它創建的線程池執行器,而不是將其留給線程池執行器(ThreadPoolExecutor) 設置默認值。

相關用法


注:本文由純淨天空篩選整理自python.org大神的英文原創作品 asyncio.loop.run_in_executor。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。