In my bash script, I need to execute two different functions, taskA and taskB, which take an integer ($i) as an argument. Since taskB $i depends on the completion of taskA $i, the following abbreviated piece of code does the job:
#!/bin/bash
taskA(){
...
}
taskB(){
...
}
for i in {1..100};
do
taskA $i
taskB $i
done
As taskA can be run at different $i independently, I can create a semaphore (taken from here Parallelize a Bash FOR Loop) and execute it in parallel. However, taskB $i requires the completion of taskA $i and the previous taskB $(i-1). Therefore, I just run them sequentially afterwards:
#!/bin/bash
open_sem(){
mkfifo pipe-$$
exec 3<>pipe-$$
rm pipe-$$
local i=$1
for((;i>0;i--)); do
printf %s 000 >&3
done
}
run_with_lock(){
local x
read -u 3 -n 3 x && ((0==x)) || exit $x
(
( "$@"; )
printf '%.3d' $? >&3
)&
}
taskA(){
...
}
taskB(){
...
}
N=36
open_sem $N
for i in {1..100};
do
run_with_lock taskA $i
done
wait
for i in {1..100};
do
taskB $i
done
In order to further optimize the procedure, is it possible to keep the semaphore for the parallel execution of taskA and run taskB simultaneously in such a way that it does not "overtake" taskA and waits for the completion of the taskA it depends on?
( taskA $i; taskB $i ) &?