2016-11-19 116 views
0

使用Python編程語言的兩個子進程來完成以下任務:創建使用python(窗口)

創建兩個進程(我們姑且稱之爲P1和P2)。 P1應打印「我是P1」,P2應打印「我是P2」。主要過程(創建P1和P2的過程)應等待它們。然後,在完成P1和P2之後,主過程應該打印出「我是主過程,這兩個過程完成了」。

+0

你嘗試過什麼?這看起來像功課。請閱讀以下http://stackoverflow.com/help/how-to-ask – Enkode

+0

,您必須出示您的嘗試。計算器是一個編程社區,而不是一門功課的社區。不管怎麼說,我寫了下面的答案,幫助您 –

回答

0

我沒有首先注意到Windows的標籤。所以我根據UNIX寫道。我不停地而不是希望它有助於將UNIX用戶too.The正確的代碼演示同一刪除答案是: -

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 
+0

你沒看到在這個問題上的Windows標籤?使用子流程模塊。 – eryksun

0

在Windows中,我們沒有系統調用fork,所以我們可以使用一個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. 

在任務管理器中捕獲的過程: - P1,P2 and Main Process 代碼輸出爲: -

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 

希望幫助!