Skip to content

Commit f81baf1

Browse files
committed
additional/bash/bg.sh: A more advanced and efficient version of the background implementation
The top version shows how to wait for all processes that you have started to finish, before new processes get spawned. This is very inefficient when you wait for example for long running disk operations. So the new iplementation solves that by starting a new process, the moment another one from the list dies. Signed-off-by: Marian Marinov <[email protected]>
1 parent 532f44a commit f81baf1

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

additional/bash/bg.sh

+31
Original file line numberDiff line numberDiff line change
@@ -24,3 +24,34 @@ for i in {1..5}; do
2424
let total--
2525
done
2626
done
27+
28+
# A more optimal solution then the above one
29+
30+
count=0
31+
# tasks will be used to store information about the pid
32+
declare -A tasks
33+
for i in {1..5}; do
34+
procs=()
35+
var=$((${RANDOM}%10+1))
36+
sleep $var &
37+
cmd_pid=$!
38+
procs+=($cmd_pid)
39+
tasks[$cmd_pid]="$i $var"
40+
41+
let count++
42+
if [[ $count -eq $max_threads ]]; then
43+
echo "Waiting for ${procs[*]}"
44+
# Wait for any task to finish.
45+
# After a task has finished, remove it from the array and reduce the count of currently running tasks.
46+
# This will allow us to start the next process immediately.
47+
pid=''
48+
wait -p pid -n ${procs}
49+
echo "Task PID: $pid finished"
50+
echo ${tasks[$pid]} >> $finished_tasks
51+
all_procs=${procs[*]}
52+
procs=( $(echo ${all_procs//$pid}) )
53+
54+
let count--
55+
fi
56+
57+
done

0 commit comments

Comments
 (0)