Sunday 20 December 2015

Python: multiprocessing: Process class


You can instantiate a process using Process class. Process starts execution, once you call the start method.
from multiprocessing import Process

def hello(name):
    print("Hello ", name)

if(__name__=="__main__"):
    p = Process(target=hello, args=('Hari',))
    p.start()
    p.join()

Run above program, you will get following output.
Hello  Hari


Following program shows process id and parent process ids.
from multiprocessing import Process
import os

def hello(name):
    print("Hello ", name)
    print("Process Id : ",os.getpid())
    print("Parent process Id : ",os.getppid())

if(__name__=="__main__"):
    p1 = Process(target=hello, args=('Hari',))
    p2 = Process(target=hello, args=('Krishna',))
    p3 = Process(target=hello, args=('PTR',))

    p1.start()
    p2.start()
    p3.start()

    p3.join()
    p2.join()
    p1.join()


Run above program, you will get following output.

Hello  Hari
Process Id :  70079
Parent process Id :  70078
Hello  Krishna
Process Id :  70080
Parent process Id :  70078
Hello  PTR
Process Id :  70081
Parent process Id :  70078


Previous                                                 Next                                                 Home

No comments:

Post a Comment