2

Use Python programming language to accomplish the following task:

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”.

Yara Emad
  • 21
  • 2
  • What have you tried? This looks like homework. Please read the following http://stackoverflow.com/help/how-to-ask – Enkode Nov 19 '16 at 07:39
  • You must show your attempt. Stackoverflow is a programming community and not a homework community. Anyways, I wrote an answer below to help you – Maharshi Roy Nov 19 '16 at 09:38

2 Answers2

4

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:- P1,P2 and Main Process 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!!

Maharshi Roy
  • 358
  • 2
  • 11
1

I didn't notice the Windows tag first. So I wrote according to UNIX. I kept the answer instead of deleting in hoping that it will aid UNIX users too.The proper code demonstrating the same is:-

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
Maharshi Roy
  • 358
  • 2
  • 11