【问题标题】:Set max concurrency with asyncio.create_subprocess_exec使用 asyncio.create_subprocess_exec 设置最大并发
【发布时间】:2018-05-11 00:01:01
【问题描述】:

我需要使用不同的输入运行一个程序大约 500 次。 我想使用asyncio.create_subprocess_exec 并希望限制同时运行的进程数,以免堵塞机器。 有没有办法设置并发级别?例如,我期望像 AbstractEventLoop.set_max_tasks 这样的东西。

【问题讨论】:

  • 使用asyncio.Semaphore

标签: python python-3.x concurrency subprocess python-asyncio


【解决方案1】:

作为@AndrewSvetlov 的suggested,您可以使用asyncio.Semaphore 来强制执行限制:

async def run_program(input):
    p = await asyncio.create_subprocess_exec(...)
    # ... communicate with the process ...
    p.terminate()
    return something_useful

async def run_throttled(input, sem):
    async with sem:
        result = await run_program(input)
    return result

LIMIT = 10

async def many_programs(inputs):
    sem = asyncio.Semaphore(LIMIT)
    results = await asyncio.gather(
        *[run_throttled(input, sem) for input in inputs])
    # ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-07
    相关资源
    最近更新 更多