Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/windows/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用python(windows)创建两个子进程_Python_Windows_Process - Fatal编程技术网

使用python(windows)创建两个子进程

使用python(windows)创建两个子进程,python,windows,process,Python,Windows,Process,使用Python编程语言完成以下任务: 创建两个进程(让我们称它们为P1和P2)。P1应打印“我是P1”,P2应打印“我是P2”。主进程(创建P1和P2的进程)应该等待它们。然后,在P1和P2完成后,主进程应该打印“我是主进程,两个进程都完成了”。我没有首先注意到Windows标记。所以我根据UNIX编写。我保留了答案而不是删除,希望它也能帮助UNIX用户。正确的代码是:- import os import time def child(id, sleepTime): print "I

使用Python编程语言完成以下任务:


创建两个进程(让我们称它们为P1和P2)。P1应打印“我是P1”,P2应打印“我是P2”。主进程(创建P1和P2的进程)应该等待它们。然后,在P1和P2完成后,主进程应该打印“我是主进程,两个进程都完成了”。

我没有首先注意到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

在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

希望有帮助

你试过什么?这看起来像是家庭作业。请阅读以下内容,您必须展示您的尝试。Stackoverflow是一个编程社区,而不是家庭作业社区。不管怎样,我在下面写了一个答案来帮助你。你没有看到这个问题上的Windows标签吗?使用子流程模块。