“Multithreading” with Bash script

Actually is not Multithreading, but the ability to run scripts in parallel and synchronization also ;)

In Linux systems each process has an associated “process identification number” (PID) that you can monitor using the “ps” application. If you want to run a process in background you just need to append the caracter “&” to the command and it will free the console for you.

So basically the script below, executes commands, gathering all PIDs and in the end it waits for them to finish:

#!/bin/bash

function jobidfromstring()
{
local STRING;
local RET;

STRING=$1;
RET=”$(echo $STRING | sed ‘s/^[^0-9]*//’ | sed ‘s/[^0-9].*$//’)”

echo $RET;
}
runmultitask()
{
JOBLIST=””
TASKLIST[0]=””
i=0

for TASK in “$@”
do
$TASK &
LASTJOB=`jobidfromstring $(jobs %%)`
JOBLIST=”$JOBLIST $LASTJOB”
TASKLIST[$i]=$TASK
i=$(($i+1))
done

i=0
for JOB in $JOBLIST ; do
wait %$JOB
echo “${TASKLIST[$i]} – Job $JOB exited with status $?”
i=$(($i+1))
done
}

runmultitask “your parallel” “your parallel”