python多进程程序的执行次序

luofeiyu
  • 1.5k

这是我的程序:

import os,time
from multiprocessing import Process

def run_proc(name):
    print('child process %s (%s) running ...' %(name,os.getpid()))
    print('process will start'+name)
    time.sleep(5)
    print('end  '+name)

if __name__ == '__main__': 
    print('parent process %s.' %os.getppid())
    for i in range(5):
        p = Process(target=run_proc,args=(str(i),))
        p.start()

time python3 test1.py
parent process 4049.
child process 0 (7054) running ...
process will start0
child process 1 (7055) running ...
process will start1
child process 3 (7057) running ...
process will start3
child process 2 (7056) running ...
process will start2
child process 4 (7058) running ...
process will start4
end 0
end 1
end 3
end 2
end 4

real 0m5.099s
user 0m0.080s
sys 0m0.008s

为何执行结果不是
time python3 test1.py
parent process 4049.
child process 0 (7054) running ...
process will start0
child process 1 (7055) running ...
process will start1
child process 2 (7057) running ...
process will start3
child process 3 (7056) running ...
process will start2
child process 4 (7058) running ...
process will start4
end 0
end 1
end 2
end 3
end 4

real 0m5.099s
user 0m0.080s
sys 0m0.008s

既然是多进程,为什么process2就一定要竞争的过process3?
你这个例子中是对stdout的竞争。
因为:process2的产生在时间上,早于process3

回复
阅读 2.4k
2 个回答

既然是多进程,为什么process2就一定要竞争的过process3?
你这个例子中是对stdout的竞争。

多进程,是并发执行的操作,这就没什么次序可言了。主程序的for循环是非常快的,几乎瞬间5个进程就全开启了,而先启动的先输出的概率大,但并不是绝对。这就跟五个运动员在同一起跑线,即使他们起跑的时间可能会有差异,有人快一点起跑,有人慢一点起跑,但是最先到终点的就不一定是最先起跑的那个人了。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏