+ -
当前位置:首页 → 问答吧 → 循环后加&就并发执行了吗?

循环后加&就并发执行了吗?

时间:2011-05-18

来源:互联网

看测试脚本
  1. [echfan@echfan-linux ~]$ cat test.sh
  2. #!/bin/bash
  3. for (( i=1;i<=5;i++ ));do
  4. echo "`date` This is >>$i" >> test.log
  5. sleep 5;
  6. echo "`date` End >>$i">>test.log
  7. done &
复制代码
执行时间是短了
  1. [echfan@echfan-linux ~]$ time bash test.sh

  2. real    0m0.017s
  3. user    0m0.003s
  4. sys     0m0.012s
复制代码
但是从输出看还是顺序执行的,在后台运行也要25秒。
  1. [echfan@echfan-linux ~]$ time bash test.sh

  2. real    0m0.017s
  3. user    0m0.003s
  4. sys     0m0.012s
  5. [echfan@echfan-linux ~]$ cat test.log
  6. Wed May 18 00:33:01 EDT 2011 This is >>1
  7. Wed May 18 00:33:06 EDT 2011 End >>1
  8. Wed May 18 00:33:06 EDT 2011 This is >>2
  9. Wed May 18 00:33:12 EDT 2011 End >>2
  10. Wed May 18 00:33:12 EDT 2011 This is >>3
  11. Wed May 18 00:33:17 EDT 2011 End >>3
  12. Wed May 18 00:33:17 EDT 2011 This is >>4
  13. Wed May 18 00:33:22 EDT 2011 End >>4
  14. Wed May 18 00:33:22 EDT 2011 This is >>5
  15. Wed May 18 00:33:27 EDT 2011 End >>5
复制代码
难道是我对并发执行的理解有误,如果让程序更短时间完成,怎么做呢?

作者: 饭碗儿   发布时间: 2011-05-18

不可能是并发的,既然是循环,就是头尾相连的,前一个没有执行完,后面就不会执行
我觉得。。

作者: where27   发布时间: 2011-05-18

用c或者升级硬件

作者: shplpy   发布时间: 2011-05-18

你的代码有问题,只是把for循环弄到后台执行了,其实还是顺序执行
应该是这样:
  1. [root@localhost ~]# cat test.sh
  2. #!/bin/bash

  3. for (( i=1;i<=5;i++ ));do
  4. sh test_per.sh $i >> test.log&

  5. done
复制代码
  1. [root@localhost ~]# cat test_per.sh
  2. echo "`date` This is >>$1" >> test.log
  3. sleep 5;
  4. echo "`date` End >>$1">>test.log
复制代码
结果:
  1. [root@localhost ~]# cat test.log
  2. 2011年 05月 18日 星期三 13:43:50 CST This is >>1
  3. 2011年 05月 18日 星期三 13:43:50 CST This is >>3
  4. 2011年 05月 18日 星期三 13:43:50 CST This is >>4
  5. 2011年 05月 18日 星期三 13:43:50 CST This is >>2
  6. 2011年 05月 18日 星期三 13:43:50 CST This is >>5
  7. 2011年 05月 18日 星期三 13:43:55 CST End >>1
  8. 2011年 05月 18日 星期三 13:43:55 CST End >>3
  9. 2011年 05月 18日 星期三 13:43:55 CST End >>4
  10. 2011年 05月 18日 星期三 13:43:55 CST End >>2
  11. 2011年 05月 18日 星期三 13:43:55 CST End >>5
复制代码

作者: yifangyou   发布时间: 2011-05-18