zoukankan      html  css  js  c++  java
  • Shell(6): 多线程操作及线程数

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

    原始的代码:

     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 "
    " 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

  • 相关阅读:
    ios -- 教你如何轻松学习Swift语法(一)
    collectionView,tableView的细节处理
    主流界面搭建原理(类似百思不得姐主界面)
    ios--时间格式化(cell业务逻辑处理)
    test
    Mac下安装Matlab R2015b
    最大奇约数
    编码问题
    最优二叉查找树
    二维数组和二级指针
  • 原文地址:https://www.cnblogs.com/lovychen/p/7735668.html
Copyright © 2011-2022 走看看