簡體   English   中英

使用asyncio.create_subprocess_exec設置最大並發

[英]Set max concurrency with asyncio.create_subprocess_exec

我需要使用不同的輸入運行一個程序大約500次。 我想使用asyncio.create_subprocess_exec並希望限制同時運行的進程數,以免阻塞計算機。 有沒有辦法設置並發級別? 例如,我期望像AbstractEventLoop.set_max_tasks這樣的東西。

如@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])
    # ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM