You are not logged in.

#1 2022-01-21 12:51:37

graysky
Wiki Maintainer
From: :wq
Registered: 2008-12-01
Posts: 10,597
Website

[shell] restrict backgrounding of jobs to 3 at a time

I am looking for a strategy to limit the number backgrounded processes in a shell script.  I can do it with GNU parallel but I would like to avoid that.  Below is a simplified script.

Running it as-is will background all of the hashes silmutaneous whereas my goal is to have them run 3 at a time max.  Any suggestions are welcomed.

#!/bin/bash
hash=( 1 2 3 4 5 6 7 8 9 )

getit() {
  echo "this is $i" ; sleep 1s
}

for i in "${hash[@]}"; do
  getit &
done

For reference, here is a working script using GNU parallel, but again, I would like to avoid it:

#!/bin/bash
hash=( 1 2 3 4 5 6 7 8 9 )

getit() {
  echo "this is $1" ; sleep 1s
}

export -f getit
parallel -j 3 getit ::: "${hash[@]}"

Last edited by graysky (2022-01-21 14:02:45)


CPU-optimized Linux-ck packages @ Repo-ck  • AUR packagesZsh and other configs

Offline

#2 2022-01-21 13:40:10

stepnem
Member
Registered: 2019-08-04
Posts: 18

Re: [shell] restrict backgrounding of jobs to 3 at a time

My first suggestion is to put 'bash' or 'shell' into the subject line.

My second suggestion is to have a look at the following:
https://mywiki.wooledge.org/ProcessMana … _at_a_time.

Offline

Board footer

Powered by FluxBB