run method

To start a new process, the run() method of the class multiprocessing.context.Process class is overridden and start() is called on the derived class instance. Alternatively, when Process is directly instantiated it calls the target argument passed through the constructor during start() call. The python examples demonstrate both the methods.

Process Updated 2 Feb 2019 1 min read

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

python
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

Output
Message added by child process

Example 2 – By inheriting from the Process class

python
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

Output
Message added by child process