bash并行执行

#!/bin/bash

for ((i=0;i<5;i++));do
        {
                sleep 3; echo "done!"
        } 
done
wait

上面这段bash脚本执行一次要耗时3x5=15秒钟 。 



但下面这段bash脚本执行完却仅耗时3秒钟

#!/bin/bash

for ((i=0;i<5;i++));do
        {
                sleep 3; echo "done!"
        } & 
done
wait

比较发现后面这个脚本仅多了一个 & 控制操作符。

&是并行执行的操作控制符,它不等一条命令执行完,另外一条命令同步执行。



参考:http://www.gnu.org/software/bash/manual/bashref.html#Lists

中的描述:If a command is terminated by the control operator ‘&’, the shell executes the command asynchronously in a subshell. This is known as executing the command in the background. The shell does not wait for the command to finish, and the return status is 0 (true). 


参考:http://www.gnu.org/software/bash/manual/bashref.html#Coprocesses

中的描述:A coprocess is executed asynchronously in a subshell, as if the command had been terminated with the ‘&’ control operator, with a two-way pipe established between the executing shell and the coprocess.


展开阅读全文

没有更多推荐了,返回首页