I have more than 10 tasks to execute, and the system restrict that there at most 4 tasks can run at the same time.
My task can be started like: myprog taskname
How can I write a bash shell script to run these task. The most important thing is that when one task finish, the script can start another immediately, making the running tasks count remain 4 all the time.
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).
You could probably do something clever with signals.
Note this is only to illustrate the concept, and thus not thoroughly tested.
Following @Parag Sardas' answer and the documentation linked here's a quick script you might want to add on your
.bash_aliases
.Relinking the doc link because it's worth a read
I.e.
./xargs-parallel.sh jobs.txt 4
maximum of 4 processes read from jobs.txtI chanced upon this thread while looking into writing my own process pool and particularly liked Brandon Horsley's solution, though I couldn't get the signals working right, so I took inspiration from Apache and decided to try a pre-fork model with a fifo as my job queue.
The following function is the function that the worker processes run when forked.
You can get a copy of my solution at Github. Here's a sample program using my implementation.
Hope this helps!
I would suggest writing four scripts, each one of which executes a certain number of tasks in series. Then write another script that starts the four scripts in parallel. For instance, if you have scripts, script1.sh, script2.sh, script3.sh, and script4.sh, you could have a script called headscript.sh like so.
Using GNU Parallel you can do:
If you have 4 cores, you can even just do:
From http://git.savannah.gnu.org/cgit/parallel.git/tree/README:
Full installation
Full installation of GNU Parallel is as simple as:
Personal installation
If you are not root you can add ~/bin to your path and install in ~/bin and ~/share:
Or if your system lacks 'make' you can simply copy src/parallel src/sem src/niceload src/sql to a dir in your path.
Minimal installation
If you just need parallel and do not have 'make' installed (maybe the system is old or Microsoft Windows):
Test the installation
After this you should be able to do:
This will send 3 ping packets to 3 different hosts in parallel and print the output when they complete.
Watch the intro video for a quick introduction: https://www.youtube.com/playlist?list=PL284C9FF2488BC6D1