1. 线程数量不可控
#!/usr/bin/bash
function do_work() {
echo "线程 $1 运行中..."
sleep 1m
}
echo "线程数量不可控演示..."
for i in {1..100}; do {
do_work $i
}&
done; wait
echo "用时 $SECONDS 秒"
2. 线程数量可控
方案1:(管道FIFO+文件描述符)
#!/usr/bin/bash
function do_work() {
echo "线程 $1 运行中..."
sleep 3s
}
f="/tmp/$$.fifo"
mkfifo $f; exec 5<>$f; rm $f
thread=5; jobs=20
echo "数量可控的多线程运行, 每次${thread}个线程..."
for i in $(seq 1 1 $thread); do echo >&5; done
for i in $(seq 1 1 $jobs); do
read -u5
{
do_work $i
echo >&5
}&
done; wait
exec 5>&-
exec 5<&-
echo "用时 $SECONDS 秒"
- 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
方案2:根据进程实时目录: /proc/pid
#!/usr/bin/bash
function do_work() {
echo "线程 $1 运行中..."
sleep 3s
}
function check_done {
old=$que; que=""; n=0
for pid in $old; do
[[ ! -d /proc/$pid ]] && continue
((n++)); que+="$pid "
done
}
thread=5; jobs=20
echo "数量可控的多线程运行, 每次${thread}个线程..."
for i in $(seq 1 1 $jobs); do
do_work $i&
que+="$! "
((n++))
while [[ $n -ge $thread ]]; do
check_done
done
done
wait
echo "用时 $SECONDS 秒"
- 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