gpt4 book ai didi

python - 使用 asyncio.create_subprocess_exec 设置最大并发数

转载 作者:行者123 更新时间:2023-12-01 01:55:13 24 4
gpt4 key购买 nike

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

最佳答案

suggested作者:@AndrewSvetlov,您可以使用 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])
# ...

关于python - 使用 asyncio.create_subprocess_exec 设置最大并发数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50283102/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com