2016-11-19 113 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 

希望帮助!