What is the correct way to multithread independent if
statements in a bash script? Is it best to place the &
after code contained in the if
or after the expression?
For an &
after the expression, it makes sense to continue threading as necessary if the if
contains a large block of code. But should one line of code also end with &
?
After the expression:
if [ expression ] &
then
#task
fi
After the task:
if [ expression ]
then
#task &
fi
Imagine 3 if
statements that all perform tasks independent of each other, how does the execution work with the different placement of the &
? From what I understand, if placed after the expression, all 3 expressions start (basically) simultaneously and so do the 3 tasks.
#Thread 1 #Thread 2 #Thread 3
if [ expr1 ] & if [ expr2 ] & if [ expr3 ] &
then then then
task1 task2 task3
fi fi fi
wait
If placed after the task code, the first if
would be evaluated and only as the first task begins would the 2nd if
be evaluated. The tasks are more staggered than simultaneous.
#Thread 1 #Thread 2 #Thread 3
if [ expr1 ]
then
task1 & if [ expr2 ]
fi then
task2 & if [ expr3 ]
fi then
task3 &
fi
wait
The expressions cannot be combined to do threading inside the if
such as:
if [ combined expression ]
then
#task1 &
#task2 &
#task3 &
fi