用shell实现任务并发数的简单控制

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

#!/bin/bash
#

CMDS[1]="echo $USER' 01 BEGIN' && sleep 6 && echo $USER' 01 END'"
CMDS[2]="echo $USER' 02 BEGIN' && sleep 3 && echo $USER' 02 END'"
CMDS[3]="echo $USER' 03 BEGIN' && sleep 7 && echo $USER' 03 END'"
CMDS[4]="echo $USER' 04 BEGIN' && sleep 4 && echo $USER' 04 END'"
CMDS[5]="echo $USER' 05 BEGIN' && sleep 2 && echo $USER' 05 END'"
CMDS[6]="echo $USER' 06 BEGIN' && sleep 5 && echo $USER' 06 END'"

N=${#CMDS[@]}

MAX=3
PIDS=''
for I in $(seq $N)
do
    while [ 1 -gt 0 ]
    do
        C=0
        pids=''
        for PID in $PIDS
        do
            ps $PID >/dev/null 2>/dev/null
            if [ $? -eq 0 ]
            then
                pids="$pids $PID"
                (( C = C + 1 ))
            fi
        done
        PIDS=$pids

        [ $C -lt $MAX ] && break
        sleep 1
    done

    #echo $i ${CMDS[$i]}
    CMD=${CMDS[$I]}
    bash -c "$CMD" &
    PIDS="$PIDS $!"
done

wait