[英]Create two child process using python(windows)
Use Python programming language to accomplish the following task: 使用Python编程语言来完成以下任务:
Create two processes (let's call them P1 and P2). 创建两个进程(我们称它们为P1和P2)。 P1 should print “I am P1”, P2 should print “I am P2”.
P1应该打印“我是P1”,P2应该打印“我是P2”。 The main process (the process that creates P1 and P2) should wait for them.
主要过程(创建P1和P2的过程)应等待它们。 Then, after P1 and P2 are done, the main process should print “I am the main process, the two processes are done”.
然后,在完成P1和P2之后,主流程应打印“我是主流程,这两个流程均已完成”。
In windows, we don't have fork system call, so we can use a python module called multiprocessing as:- 在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.
The processes as captured in task manager:- 任务管理器中捕获的过程:-
The code output was:-
代码输出为:-
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
Hope that helps!! 希望有帮助!!
I didn't notice the Windows tag first. 我没有首先注意到Windows标记。 So I wrote according to UNIX.
所以我根据UNIX写的。 I kept the answer instead of deleting in hoping that it will aid UNIX users too.The proper code demonstrating the same is:-
我保留了答案而不是删除,希望它也能对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
I executed 我执行了
time python fork.py
The output was as expected:- 输出符合预期:
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.