-
Notifications
You must be signed in to change notification settings - Fork 5
/
threads
executable file
·49 lines (37 loc) · 1.05 KB
/
threads
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#!/bin/bash
# number of threads
threads=10
# list of targets
targets=(foo bar baz)
# the function thaht's being threaded. "$1" is the current target
threadfn() {
sleep "$((RANDOM % 10))"
# print newline to the fifo at the end, so we know it finished
echo >&3
}
trap 'trap -- INT; echo "waiting for jobs to complete..."; wait; exit' INT
if ! { fifo=$(mktemp -u) && mkfifo"$fifo"; }; then
printf "error creating fifo \`%s'\n" "$fifo" >&2
exit 1
fi
# tie fd to fifo, find total number of targets
exec 3<>"$fifo"
tot=${#targets[@]}
# launch initial threads
for ((cur=0; cur<threads; cur++)); do
((cur < tot)) && threadfn "${targets[cur]}" &
done
# stores number of finished threads
fin=0
# each time a line is written to the fifo, a thread finished
while read -r <&3; do
# if there are more to launch, launch one
if ((cur < tot)); then
threadfn "${targets[cur]}" &
fi
# increment current and number of finished. if the number finished equals
# the total, break the loop
((cur++, ++fin == tot)) && break
done
# close the fd/fifo
exec 3>&-