在bash中,使用后台任务来实现任务的“多进程化”。在不加控制的模式下,不管有多少 任务,全部都后台执行。也就是说,在这种情况下,有多少任务就有多少“进程”在同时执行。我们就先实现第一种情况:
实例一:正常情况脚本
#
!/bin/bash
for ((i =
0 ;i <
5 ;i ++ ));
do

{
sleep
3 ;echo
1 >> aa && echo
"
done!
"

}

done
wait

cat aa | wc - l

rm aa
这种情况下,程序顺序执行,每个循环3s,共需15s左右。

$
time bash test . sh

done !

done !

done !

done !

done !
5

real 0m15 . 030s

user 0m0 . 002s

sys 0m0 . 003s
实例二:“多进程”实现
#
!/bin/bash
for ((i =
0 ;i <
5 ;i ++ ));
do

{
sleep
3 ;echo
1 >> aa && echo
"
done!
"

} &

done
wait

cat aa | wc - l

rm aa
这个实例实际上就在上面基础上多加了一个后台执行&符号,此时应该是5个循环任务并发执行,最后需要3s左右时间。

$
time bash test . sh

done !

done !

done !

done !

done !
5

real 0m3 . 011s

user 0m0 . 002s

sys 0m0 . 004s
效果非常明显。
这里需要说明一下wait的左右。wait是等待前面的后台任务全部完成才往下执行,否则程序本身是不会等待的,这样对后面依赖前面任务结果的命令 来说就可能出错。例如上面wc -l的命令就报错:不存在aa这个文件。
wait命令的官方解释如下:

wait [n]

Wait for the specified process and return its termination status. n may be a process ID or a job specification; if a job spec is given, all processes in that job's pipeline are waited for. If n is not given, all currently active child processes are waited for, and the return status is zero. If n specifies a non-existent process or job, the return status is 127. Otherwise, the return status is the exit status of the last processor job waited for.
以上所讲的实例都是进程数目不可控制的情况,下面描述如何准确控制并发的进程数目。
sleep 3s,线程数为15,一共循环50次,所以,此脚本一共的执行时间大约为12秒
即:
15×3=45, 所以 3 x 3s = 9s
(50-45=5)<15, 所以 1 x 3s = 3s
所以 9s + 3s = 12s
$ time ./multithread.sh >/dev/null
real 0m12.025s
user 0m0.020s
sys 0m0.064s
而当不使用多线程技巧的时候,执行时间为:50 x 3s = 150s。
此程序中的命令

mkfifo tmpfile
和linux中的命令

mknod tmpfile p
效果相同。区别是mkfifo为POSIX标准,因此推荐使用它。该命令创建了一个先入先出的管道文件,并为其分配文件标志符6。管道文件是进程之 间通信的一种方式,注意这一句很重要
exec
6 <>
$tmp_fifofile
#
将fd6指向fifo类型
如果没有这句,在向文件$tmp_fifofile或者 &6写入数据时,程序会被阻塞,直到有read读出了管道文件中的数据为止。而执行了上面这一句后就可以在程序运行期间 不断向fifo类 型的文件写入数据而不会阻塞,并且数据会被保存下来以供read程序读出。
原文地址:http://www.linuxschool.net/linux-shell-bash-mp.html