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

Viewed 12198

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 ]
  sleep $t && echo $f $t &
done
wait
7 Answers

This is my "parallel" unzip loop using bash on AIX:

for z in *.zip ; do
  7za x $z >/dev/null
  while [ $(jobs -p|wc -l) -ge 4 ] ; do
    wait -n
  done
done

Notes:

  • jobs -p (bash function) lists jobs of immediate parent
  • wait -n (bash function) waits for any (one) background process to finish
Related