Introduction to Multiprocessing

In the series of intermediate python, now we will discuss ‘Multiprocessing in Python’.

Multiprocessing is the functionality which may allow your system to use multiple cores of your processor. It will increase efficiency. Sometimes it happens that one processor is overloaded with all processes. So, with the help of Multiprocessing, we are giving processes to different processors.

Multiprocessing executes multiple processes simultaneously.

Why do we need multiprocessing?

Suppose, we have multiple tasks to do. So, for keeping track of all task by one processor is difficult. Hence, multiprocessing is needed here.

We will see the example of how to perform multiprocessing using multiprocessing package in Python.

Here we are creating two processes one for addition and subtraction and we will see that they are executing independently.

Importing module:

import multiprocessing
import os
Addition function
In [2]:
def add(a,b):
    print("Addition of two numbers {}".format(a+b))
    print("ID of process addition: {}".format(os.getpid()))
Subtraction function
In [3]:
def sub(c,d):
    print("Subtraction of two numbers {}".format(c-d))
    print("ID of process subtraction: {}".format(os.getpid()))
This is our main process which is executing both the processes. Here we are keeping track of ids of the processes and our main process.
If you are using join then the whole method will execute according. If you are not putting join, then random execution of process will occur.
In [4]:
if __name__ == "__main__": 
    print("ID of main process: {}".format(os.getpid())) 
    # creating processes 
    p1 = multiprocessing.Process(target=add, args=(10,11)) 
    p2 = multiprocessing.Process(target=sub, args=(11,10)) 
    # starting process 1 
    # starting process 2 
    # wait until process 1 is finished 
    # wait until process 2 is finished 
    # both processes finished 

Now, if we will execute this code. It will work in the command line.

This is the output when we applied join in our main method.

These are the outputs when we didn’t use join in our method. See both have different outputs.

So, this is all for an introduction to Multiprocessing. In next blog, we will cover how to pass information from one process to another.

Stay tune! Enjoy learning with us!

Leave a Reply

Your email address will not be published. Required fields are marked *