当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。