[英]Create two child process using python(windows)
使用Python編程語言來完成以下任務:
創建兩個進程(我們稱它們為P1和P2)。 P1應該打印“我是P1”,P2應該打印“我是P2”。 主要過程(創建P1和P2的過程)應等待它們。 然后,在完成P1和P2之后,主流程應打印“我是主流程,這兩個流程均已完成”。
在Windows中,我們沒有fork系統調用,因此我們可以使用稱為multiprocessing的python模塊:
from multiprocessing import Process, Lock
import time
import os
def f(lock,id,sleepTime):
lock.acquire()
print "I'm P"+str(id)+" Process ID: "+str(os.getpid())
lock.release()
time.sleep(sleepTime) #sleeps for some time
if __name__ == '__main__':
print "Main Process ID: "+str(os.getpid())
lock=Lock()
p1=Process(target=f, args=(lock,1,3,)) #P1 sleeps for 3 seconds
p2=Process(target=f, args=(lock,2,5,)) #P2 sleeps for 5 seconds
start=time.time()
p1.start()
p2.start()
p1.join()
p2.join()
end=time.time()
print "I am the main process, the two processes are done"
print "Time taken:- "+str(end-start)+"secs" #MainProcess terminates at approx ~ 5 secs.
Main Process ID: 9804
I'm P1 Process ID: 6088
I'm P2 Process ID: 4656
I am the main process, the two processes are done
Time taken:- 5.15300011635secs
希望有幫助!!
我沒有首先注意到Windows標記。 所以我根據UNIX寫的。 我保留了答案而不是刪除,希望它也能對UNIX用戶有所幫助。演示相同代碼的正確代碼是:-
import os
import time
def child(id, sleepTime):
print "I'm P"+str(id)
time.sleep(sleepTime)
os._exit(0)
p1=os.fork()
if (p1==0):
child(1,3) #P1 sleeps for 3 seconds
p2=os.fork()
if (p2==0):
child(2,5) #P2 sleeps for 5 seconds
if (p1>0 and p2>0):
os.waitpid(p1,0) #Waiting for child 1
os.waitpid(p2,0) #Waiting for child2
print "I am the main process, the two processes are done" #Printed after approx 5 seconds
我執行了
time python fork.py
輸出符合預期:
I'm P1
I'm P2
I am the main process, the two processes are done
real 0m5.020s
user 0m0.004s
sys 0m0.008s
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.