簡體   English   中英

如何在異步python中使用子進程模塊限制並發進程數

[英]How to limit the number of concurrent processes using subprocess module in asyncio python

import asyncio
import asyncio.subprocess
args="blah blah argument "     
create=asyncio.create_subprocess_shell(args,stdout=asyncio.subprocess.PIPE)
proc = await create
output= await proc.stdout.read( )

這是我的服務器代碼的一部分,它從客戶端獲得了數以千計的並行點擊。現在我應該如何限制服務器創建的運行參數blah blah的最大子進程數。 因為這是代碼正在使用我100%的cpu。 我需要在smae cpu上部署其他服務器

asyncio.Semaphore是一種限制並發作業內部計數器的方法:

sem = asyncio.Semaphore(10)

async def do_job(args):
    async with sem:  # Don't run more than 10 simultaneous jobs below
        proc = await asyncio.create_subprocess_shell(args, stdout=PIPE)
        output = await proc.stdout.read()
        return output

請注意,您應該確定作業數量的增加不會比實際完成的速度快得多。 否則,您將需要比這更復雜的東西。

暫無
暫無

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

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