关于脚本的含义请参照:
http://www.cnitblog.com/sysop/archive/2008/11/03/50974.aspx 【BASH实现“多线程”】
我只是对它的范例做了一些函数的封装,便于代码块的引用。
- #!/bin/bash
- # Init thread pool
- # Usage: Thread_init 10 , init 10 thread pool
- Thread_init(){
- tmp_fifofile="/tmp/$$.fifo"
- mkfifo $tmp_fifofile
- exec 6<>$tmp_fifofile
- rm $tmp_fifofile
- [ $# -ne 0 ] && thread=$@ || thread=5 # default thread is 5
- for ((i=0;i<$thread;i++))
- do
- echo
- done >&6
- }
- # Check function sub is exist
- # Usage: Check_cmd "Thread_init 15" ,if Thread_init function is exist, return 0 ,else return 1.
- Check_cmd(){
- if [ $# -ne 0 ];then
- type "$1" &> /dev/null
- RET=$?
- [ ${RET} -eq 0 ] && return 0 || return ${RET}
- else return 1
- fi
- }
- # Thread main functiion
- # Usage: Thread sub, sub is the function of the sub proc.
- Thread(){
- read -u6
- {
- # $@ is the parameters about threads
- "$@" && {
- echo "Thread $i is finished"
- } || {
- echo "Thread $i error!!! "
- }
- echo >&6
- } &
- pid=$!
- echo "Thread $i is started [$pid]"
- }
- # Wait sub proc finined
- # Usage Thread_wait
- Thread_wait(){
- wait
- exec 6>&-
- return 0
- }
- # Sub fun
- # Usage: DIY
- sub(){
- sleep 3
- }
- # Main
- if Check_cmd sub; then
- RET=$?
- # DIY BEGIN
- Thread_init 15 # 初始化线程池
- for i in `seq 75`
- do
- Thread sub # sub为调用的子进程函数,可以在后边加参数
- done
- Thread_wait && exit $? # 等待子进程都执行完毕后退出
- # DIY END
- else
- exit ${RET}
- fi
通过time测试很容易发现,线程池,开15个,75个子进程,需要3s*(75/15)=15s
real 0m15.026s
user 0m0.027s
sys 0m0.071s
模拟的效果还不错。
现在我们可以修改
# DIY BEGIN
Thread_init 15 # 初始化线程池
for i in `seq 75`
do
Thread sub # sub为调用的子进程函数,可以在后边加参数
done
Thread_wait && exit $? # 等待子进程都执行完毕后退出
# DIY END
上面一部分的逻辑,以及脚本中的sub子进程函数。例如,我可以用它来ssh方式批量上传,大家尽管发挥想像力好了,有好的应用,也给大家分享一下。
附件:http://down.51cto.com/data/2359657
本文转自xiaoyuwang 51CTO博客,原文链接:http://blog.51cto.com/wangxiaoyu/762880,如需转载请自行联系原作者