在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Python  網(wǎng)絡(luò)安全/ python多進(jìn)程程序的執(zhí)行次序

python多進(jìn)程程序的執(zhí)行次序

這是我的程序:

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

為何執(zhí)行結(jié)果不是
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

既然是多進(jìn)程,為什么process2就一定要競(jìng)爭(zhēng)的過process3?
你這個(gè)例子中是對(duì)stdout的競(jìng)爭(zhēng)。
因?yàn)椋簆rocess2的產(chǎn)生在時(shí)間上,早于process3

回答
編輯回答
法克魷

多進(jìn)程,是并發(fā)執(zhí)行的操作,這就沒什么次序可言了。主程序的for循環(huán)是非??斓?,幾乎瞬間5個(gè)進(jìn)程就全開啟了,而先啟動(dòng)的先輸出的概率大,但并不是絕對(duì)。這就跟五個(gè)運(yùn)動(dòng)員在同一起跑線,即使他們起跑的時(shí)間可能會(huì)有差異,有人快一點(diǎn)起跑,有人慢一點(diǎn)起跑,但是最先到終點(diǎn)的就不一定是最先起跑的那個(gè)人了。

2018年9月4日 10:02
編輯回答
不將就

既然是多進(jìn)程,為什么process2就一定要競(jìng)爭(zhēng)的過process3?
你這個(gè)例子中是對(duì)stdout的競(jìng)爭(zhēng)。

2018年8月24日 09:52