How to limit number of threads/sub-processes used in a function in bash

后端 未结 6 1712
甜味超标
甜味超标 2020-11-27 03:32

My question is how change this code so it will use only 4 threads/sub-processes?

TESTS=\"a b c d e\"

for f in $TESTS; do
  t=$[ ( $RANDOM % 5 )  + 1 ]
  sl         


        
6条回答
  •  没有蜡笔的小新
    2020-11-27 04:16

    This tested script runs 5 jobs at a time and will restart a new job as soon as it does (due to the kill of the sleep 10.9 when we get a SIGCHLD. A simpler version of this could use direct polling (change the sleep 10.9 to sleep 1 and get rid of the trap).

    #!/usr/bin/bash
    
    set -o monitor
    trap "pkill -P $$ -f 'sleep 10\.9' >&/dev/null" SIGCHLD
    
    totaljobs=15
    numjobs=5
    worktime=10
    curjobs=0
    declare -A pidlist
    
    dojob()
    {
      slot=$1
      time=$(echo "$RANDOM * 10 / 32768" | bc -l)
      echo Starting job $slot with args $time
      sleep $time &
      pidlist[$slot]=`jobs -p %%`
      curjobs=$(($curjobs + 1))
      totaljobs=$(($totaljobs - 1))
    }
    
    # start
    while [ $curjobs -lt $numjobs -a $totaljobs -gt 0 ]
     do
      dojob $curjobs
     done
    
    # Poll for jobs to die, restarting while we have them
    while [ $totaljobs -gt 0 ]
     do
      for ((i=0;$i < $curjobs;i++))
       do
        if ! kill -0 ${pidlist[$i]} >&/dev/null
         then
          dojob $i
          break
         fi
       done
       sleep 10.9 >&/dev/null
     done
    wait
    

提交回复
热议问题