Task required: When I need to compress the files in a folder separately:
The original code:
1 #!/usr/bin/shell2 function Getdir () {3 forElementinch' LS $`4 Do5 #Echo $element6Dir_or_file=$1$element7 8 #Echo $dir _or_file9 if[ -d $dir _or_file]Ten Then One #echo Tar cvf tar_data/$element. Tar $dir _or_file A' Zip-q-R. /tar_data/$element. zip $dir _or_file ' - fi - Done the } -Root_dir="" -Getdir $root _dir
Code for multithreaded compression:
It is very simple to change to a multithreaded implementation, with the braces plus the & symbol at the back of do, plus a wait after done, indicating that the parent process waits for the child process to exit before exiting.
In Linux, a symbol at the end of the command &
indicates that the command will be executed in the background so that subsequent commands do not have to wait for the previous command to complete before they can begin execution. The loop body in the example has multiple commands, so you can {}
enclose it and add a symbol after the curly brace &
.
1#!/usr/bin/Shell2 functionGetdir () {3 forElementinch`ls$1`4 Do5 {6#Echo$element7dir_or_file=$1$element8 9#Echo$dir _or_fileTen if[ -d $dir _or_file] One Then A#Echo TarCVF tar_data/$element.Tar$dir _or_file -`Zip-q-r. /tar_data/$element.Zip$dir _or_file ' - fi the}& - Done - wait - } +Root_dir="" -Getdir $root _dir
Code that controls the number of threads:
#!/usr/bin/Shellthread_num=3#定义描述符为9的管道Mkfifotmpexec9<>tmp# writes a specified number of newline characters in advance, and a newline character represents a process for((i=0;i< $THREAD _num;i++)) Do Echo-ne"\ n" 1>&9 DonefunctionGetdir () { forElementinch`ls$1` Do{Read-U9 { #Echo$element Dir_or_file=$1$element #Echo$dir _or_fileif[ -d $dir _or_file] Then #Echo TarCVF 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
Reference Source:
Http://www.cnblogs.com/signjing/p/7074778.html
Http://m.jb51.net/article/51720.htm
Shell multithreading operations and number of threads