Run method

Method Name:

run

Method Signature:

run()

Return Value:

NoneType

Method Overview:

  • The contents of the run() method constitute what is to be executed as a process.
  • run() method can be used in any of the following two ways:
    • The run method of the multiprocessing.context.Process calls the callable object passed through the target parameter of the multiprocessing.context.Process constructor.

 

  • Inheriting the multiprocessing.context.Process class and overriding the run() method, makes the derived class instance to be started as a process. Inside the overridden run() method, the __init__() method of the parent class context.Process has to be called first.

Parameters:

Not Applicable

 

Example 1 – Through the target parameter of the Process constructor:

import multiprocessing as multiproc

 

def pf(mq):

    mq.put("Message added by child process");

 

if __name__ == '__main__':

    multiproc.set_start_method('fork')

    mq = multiproc.Queue()

   

    cp = multiproc.Process(target = pf, args=(mq,),name="MultiProc Example1")

    cp.start()

    cp.join()

   

    print(mq.get())

 

Output:

Message added by child process

 

Example 2 – By inheriting from the Process class:

import multiprocessing as multiproc

 

class SimpleProc(multiproc.context.Process):

    def __init__(self, mq):

        multiproc.context.Process.__init__(self)

        self.mq = mq

  

    def run(self):

        mq.put("Message added by child process");

 

if __name__ == '__main__':

    multiproc.set_start_method('fork')

    mq = multiproc.Queue()

   

    cp = SimpleProc(mq)

    cp.start()

    cp.join()

   

    print(mq.get())

 

 

Output:

Message added by child process

 

 

 


Copyright 2024 © pythontic.com