Linux Shell实现\"多进程\"编程

以梦为马不负韶华 2012-09-02

单进程模式代码:

#!/bin/sh

plus=0;
t1=`date +%s`
sub_fun()
{
	index="${1}"
	for i in {1..4}; do
		echo "sub_fun $index, loop:$i"
		plus=$[$plus + 1]
		sleep 1
	done
}

echo "Begin run on time: `date +%T`"
for j in {1..3}; do
{
	sub_fun "$j"
}
done

t2=`date +%s`
echo "End run on time: `date +%T`, plus sum:$plus, run time:$[ $t2 - $t1 ]"
 

单进程运行结果:

Begin run on time: 18:56:01
sub_fun 1, loop:1
sub_fun 1, loop:2
sub_fun 1, loop:3
sub_fun 1, loop:4
sub_fun 2, loop:1
sub_fun 2, loop:2
sub_fun 2, loop:3
sub_fun 2, loop:4
sub_fun 3, loop:1
sub_fun 3, loop:2
sub_fun 3, loop:3
sub_fun 3, loop:4
End run on time: 18:56:13, plus sum:12, run time:12
 

多进程模式代码:

#!/bin/sh

plus=0;
t1=`date +%s`
file_path="file.eml"
sub_fun()
{
	index="${1}"
	file_path="${2}"
	for i in {1..4}; do
		echo "[`date +%T`]sub_fun $index, file:$file_path, loop:$i"
		plus=$[$plus + 1]
		sleep 1
	done
}

echo "Begin run on time: `date +%T`"
for j in {1..3}; do
{
	sub_fun "$j" "$file_path$j"
} &
done

wait
t2=`date +%s`
echo "End run on time: `date +%T`, plus sum:$plus, run time:$[ $t2 - $t1 ]"
 

多进程运行结果:

Begin run on time: 20:55:40
[20:55:40]sub_fun 1, file:file.eml1, loop:1
[20:55:40]sub_fun 2, file:file.eml2, loop:1
[20:55:40]sub_fun 3, file:file.eml3, loop:1
[20:55:41]sub_fun 1, file:file.eml1, loop:2
[20:55:41]sub_fun 2, file:file.eml2, loop:2
[20:55:41]sub_fun 3, file:file.eml3, loop:2
[20:55:42]sub_fun 1, file:file.eml1, loop:3
[20:55:42]sub_fun 2, file:file.eml2, loop:3
[20:55:42]sub_fun 3, file:file.eml3, loop:3
[20:55:43]sub_fun 2, file:file.eml2, loop:4
[20:55:43]sub_fun 1, file:file.eml1, loop:4
[20:55:43]sub_fun 3, file:file.eml3, loop:4
End run on time: 20:55:44, plus sum:0, run time:4
 

奇怪,为什么多进程模式下,plus最后结果是0?

相关推荐