码迷,mamicode.com
首页 > 编程语言 > 详细

Shell 多线程操作及线程数

时间:2017-10-26 11:38:34      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:换行符   描述符   描述   data   www.   one   htm   nbsp   大括号   

任务需要:当我需要对一个文件夹中的文件,分别压缩的时候:

原始的代码:

 1 #!/usr/bin/shell
 2 function getdir(){
 3     for element in `ls $1`
 4     do
 5         #echo $element
 6         dir_or_file=$1$element
 7 
 8         #echo $dir_or_file
 9         if [ -d $dir_or_file ]
10         then
11             #echo tar cvf tar_data/$element.tar $dir_or_file
12             `zip -q -r ../tar_data/$element.zip $dir_or_file`
13         fi
14     done
15 }
16 root_dir=""
17 getdir $root_dir

多线程压缩的代码:

改成多线程实现非常简单,只需要在do后面的大括号加 & 符号,在done后面加一个wait,表示父进程等待子进程退出后再退出。

在linux中,在命令的末尾加上&符号,则表示该命令将在后台执行,这样后面的命令不用等待前面的命令执行完就可以开始执行了。示例中的循环体内有多条命令,则可以以{}括起来,在大括号后面添加&符号。

 1 #!/usr/bin/shell
 2 function getdir(){
 3     for element in `ls $1`
 4     do
 5     {
 6         #echo $element
 7         dir_or_file=$1$element
 8 
 9         #echo $dir_or_file
10         if [ -d $dir_or_file ]
11         then
12             #echo tar cvf tar_data/$element.tar $dir_or_file
13             `zip -q -r ../tar_data/$element.zip $dir_or_file`
14         fi
15     }&
16     done 
17     wait
18 }
19 root_dir=""
20 getdir $root_dir

控制多线程个数的代码:

 

#!/usr/bin/shell

THREAD_NUM=3
#定义描述符为9的管道
mkfifo tmp
exec 9<>tmp
#预先写入指定数量的换行符,一个换行符代表一个进程
for ((i=0;i<$THREAD_NUM;i++))
do
    echo -ne "\n" 1>&9
done

function getdir(){
    for element in `ls $1`
    do
    {
        read -u 9
        {
            #echo $element
            dir_or_file=$1$element

            #echo $dir_or_file
            if [ -d $dir_or_file ]
            then
                #echo tar cvf tar_data/$element.tar $dir_or_file
                `zip -q -r ../tar_data/$element.zip $dir_or_file`
            fi
         }&
    }
    done
    wait
}
root_dir=""
getdir $root_dir

 

参考来源:

http://www.cnblogs.com/signjing/p/7074778.html

http://m.jb51.net/article/51720.htm

Shell 多线程操作及线程数

标签:换行符   描述符   描述   data   www.   one   htm   nbsp   大括号   

原文地址:http://www.cnblogs.com/lovychen/p/7735668.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!