使用 python(windows) 创建两个子进程 [英] Create two child process using python(windows)

查看:34
本文介绍了使用 python(windows) 创建两个子进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Use Python programming language to accomplish the following task:

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

Create two processes (let’s call them P1 and P2). P1 should print "I am P1", P2 should print "I am P2". The main process (the process that creates P1 and P2) should wait for them. Then, after P1 and P2 are done, the main process should print "I am the main process, the two processes are done".

推荐答案

在 windows 中,我们没有 fork 系统调用,所以我们可以使用名为 multiprocessing 的 python 模块:-

In windows, we don't have fork system call, so we can use a python module called multiprocessing as:-

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

希望有帮助!!

这篇关于使用 python(windows) 创建两个子进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆