The Wayback Machine - https://web.archive.org/web/20240912231252/https://www.geeksforgeeks.org/multiprocessing-python-set-1/
Open In App

Multiprocessing in Python | Set 1 (Introduction)

Last Updated : 13 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

This article is a brief yet concise introduction to

multiprocessing

in Python programming language.

What is multiprocessing?

Multiprocessing refers to the ability of a system to support more than one processor at the same time. Applications in a multiprocessing system are broken to smaller routines that run independently. The operating system allocates these threads to the processors improving performance of the system.

Why multiprocessing?

Consider a computer system with a single processor. If it is assigned several processes at the same time, it will have to interrupt each task and switch briefly to another, to keep all of the processes going. This situation is just like a chef working in a kitchen alone. He has to do several tasks like baking, stirring, kneading dough, etc. So the gist is that: The more tasks you must do at once, the more difficult it gets to keep track of them all, and keeping the timing right becomes more of a challenge. This is where the concept of multiprocessing arises!

A multiprocessing system can have:

  • multiprocessor, i.e. a computer with more than one central processor.
  • multi-core processor, i.e. a single computing component with two or more independent actual processing units (called “cores”).

Here, the CPU can easily executes several tasks at once, with each task using its own processor. It is just like the chef in last situation being assisted by his assistants. Now, they can divide the tasks among themselves and chef doesn’t need to switch between his tasks.

Multiprocessing in Python

In Python, the

multiprocessing

module includes a very simple and intuitive API for dividing work between multiple processes. Let us consider a simple example using multiprocessing module:

Python
# importing the multiprocessing module
import multiprocessing

def print_cube(num):
    """
    function to print cube of given num
    """
    print("Cube: {}".format(num * num * num))

def print_square(num):
    """
    function to print square of given num
    """
    print("Square: {}".format(num * num))

if __name__ == "__main__":
    # creating processes
    p1 = multiprocessing.Process(target=print_square, args=(10, ))
    p2 = multiprocessing.Process(target=print_cube, args=(10, ))

    # starting process 1
    p1.start()
    # starting process 2
    p2.start()

    # wait until process 1 is finished
    p1.join()
    # wait until process 2 is finished
    p2.join()

    # both processes finished
    print("Done!")
Square: 100
Cube: 1000
Done!

Let us try to understand the above code:

  • To import the multiprocessing module, we do:
    import multiprocessing
  • To create a process, we create an object of Process class. It takes following arguments:
    • target: the function to be executed by process
    • args: the arguments to be passed to the target function
    Note: Process constructor takes many other arguments also which will be discussed later. In above example, we created 2 processes with different target functions:
    p1 = multiprocessing.Process(target=print_square, args=(10, ))
    p2 = multiprocessing.Process(target=print_cube, args=(10, ))
  • To start a process, we use start method of Process class.
    p1.start()
    p2.start()
  • Once the processes start, the current program also keeps on executing. In order to stop execution of current program until a process is complete, we use join method.
    p1.join()
    p2.join()
    As a result, the current program will first wait for the completion of p1 and then p2. Once, they are completed, the next statements of current program are executed.

Let us consider another program to understand the concept of different processes running on same python script. In this example below, we print the ID of the processes running the target functions:

Python
# importing the multiprocessing module
import multiprocessing
import os

def worker1():
    # printing process id
    print("ID of process running worker1: {}".format(os.getpid()))

def worker2():
    # printing process id
    print("ID of process running worker2: {}".format(os.getpid()))

if __name__ == "__main__":
    # printing main program process id
    print("ID of main process: {}".format(os.getpid()))

    # creating processes
    p1 = multiprocessing.Process(target=worker1)
    p2 = multiprocessing.Process(target=worker2)

    # starting processes
    p1.start()
    p2.start()

    # process IDs
    print("ID of process p1: {}".format(p1.pid))
    print("ID of process p2: {}".format(p2.pid))

    # wait until processes are finished
    p1.join()
    p2.join()

    # both processes finished
    print("Both processes finished execution!")

    # check if processes are alive
    print("Process p1 is alive: {}".format(p1.is_alive()))
    print("Process p2 is alive: {}".format(p2.is_alive()))
ID of main process: 28628
ID of process running worker1: 29305
ID of process running worker2: 29306
ID of process p1: 29305
ID of process p2: 29306
Both processes finished execution!
Process p1 is alive: False
Process p2 is alive: False
  • The main python script has a different process ID and multiprocessing module spawns new processes with different process IDs as we create Process objects p1 and p2. In above program, we use os.getpid() function to get ID of process running the current target function. Notice that it matches with the process IDs of p1 and p2 which we obtain using pid attribute of Process class.
  • Each process runs independently and has its own memory space.
  • As soon as the execution of target function is finished, the processes get terminated. In above program we used is_alive method of Process class to check if a process is still active or not.

Consider the diagram below to understand how new processes are different from main Python script:

So, this was a brief introduction to multiprocessing in Python. Next few articles will cover following topics related to multiprocessing:

  • Sharing data between processes using Array, value and queues.
  • Lock and Pool concepts in multiprocessing

Next:

References:

Multiprocessing in Python | Set 1 (Introduction) – FAQs

What is the Introduction of Multiprocessing?

Multiprocessing refers to the ability of a system to support more than one processor and/or the ability to allocate tasks between them. In the context of programming, particularly in Python, multiprocessing involves using multiple processes, rather than threads, to execute code concurrently. This allows a program to leverage multiple CPU cores for intensive computing tasks, bypassing the limitations imposed by the Global Interpreter Lock (GIL) in Python.

The 4 Essential Parts of Multiprocessing in Python

Multiprocessing in Python involves several key components that allow efficient parallel execution of tasks:

  1. Process: The Process class is used to create and manage independent processes. Each process runs in its own memory space.
  2. Queue: The Queue class is a shared job queue that allows process-safe data exchange and coordination between processes. It’s used for passing messages or results between process instances.
  3. Pipe: Pipes provide a way to establish a communication channel between processes. They are useful for bidirectional communication between two processes.
  4. Lock: Locks are used to ensure that only one process is executing a certain section of code at a time. This prevents data corruption by synchronizing access to shared resources.
from multiprocessing import Process, Queue, Pipe, Lock

def worker(q, lock):
with lock:
print("Task executed")
q.put("Data")

if __name__ == "__main__":
q = Queue()
lock = Lock()
p = Process(target=worker, args=(q, lock))
p.start()
p.join()
print(q.get()) # Output "Data"

What is the Main Function of Multiprocessing?

The main function of multiprocessing in Python is to run separate memory-space processes and effectively parallelize Python code to utilize multiple CPU cores at once. This is particularly advantageous for CPU-bound and I/O-bound tasks where performance can be significantly improved over using threading due to the GIL in Python.

What are the Benefits of Multiprocessing in Python?

The benefits of using multiprocessing in Python include:

  • Improved Performance: By running multiple processes concurrently, each on its own processor or core, multiprocessing can significantly reduce the time required for executing tasks.
  • Avoiding GIL Limitations: Unlike threading, multiprocessing does not suffer from Python’s GIL issues because each process runs in its own Python interpreter.
  • Better Resource Utilization: It allows for the effective utilization of multiple CPUs within a machine, which can lead to better handling of resource-intensive tasks.

When Was Multiprocessing Introduced in Python?

The multiprocessing module was introduced in Python 2.6 in 2008 and has been available in Python 3.x since its inception. This module was designed as a part of the standard library to provide process-based “threading” interface to leverage multiple CPUs for better performance.



Similar Reads

Python multiprocessing.Queue vs multiprocessing.manager().Queue()
In Python, the multiprocessing module allows for the creation of separate processes that can run concurrently on different cores of a computer. One of the ways to communicate between these processes is by using queues. The multiprocessing module provides two types of queues: The Queue class is a simple way to create a queue that can be used by mult
10 min read
Multiprocessing in Python | Set 2 (Communication between processes)
Multiprocessing in Python | Set 1 These articles discusses the concept of data sharing and message passing between processes while using multiprocessing module in Python. In multiprocessing, any newly created process will do following: run independently have their own memory space. Consider the program below to understand this concept: import multi
9 min read
Difference Between Multithreading vs Multiprocessing in Python
In this article, we will learn the what, why, and how of multithreading and multiprocessing in Python. Before we dive into the code, let us understand what these terms mean. A program is an executable file which consists of a set of instructions to perform some task and is usually stored on the disk of your computer.A process is what we call a prog
8 min read
Running Queries in Python Using Multiprocessing
Before diving into running queries using multiprocessing let’s understand what multiprocessing is in Python. Multiprocessing enables the computer to utilize multiple cores of a CPU to run tasks/processes in parallel. This parallelization leads to significant speedup in tasks that involve a lot of computation. Some of you might be wondering why don’
3 min read
Multithreading or Multiprocessing with Python and Selenium
Multithreading and multiprocessing are two popular approaches for improving the performance of a program by allowing it to run tasks in parallel. These approaches can be particularly useful when working with Python and Selenium, as they allow you to perform multiple actions simultaneously, such as automating the testing of a web application. In thi
11 min read
Understanding ‘fork’ and ‘spawn’ in Python Multiprocessing
Python’s multiprocessing library provides a powerful way to leverage multiple processor cores for concurrent execution, enhancing the performance of computationally intensive tasks. One of the intriguing aspects of multiprocessing is the ability to initiate new processes using various start methods. These start methods not only facilitate the creat
6 min read
Python Database Optimization with Psycopg2 and Multiprocessing
This article will provide a succinct overview of the fundamental utilization of the Psycopg2 module and the Multiprocessing module in Python. It will cover how Psycopg2 operates independently and in conjunction with multiprocessing. Psycopg2 and Its Role in Database OperationsAccording to PyPi's documentation for Psycopg2, it is designed to be used
6 min read
Multiprocessing with NumPy Arrays
Multiprocessing is a powerful tool that enables a computer to perform multiple tasks at the same time, improving overall performance and speed. In this article, we will see how we can use multiprocessing with NumPy arrays. NumPy is a library for the Python programming language that provides support for arrays and matrices. In many cases, working wi
5 min read
Multiprocessing in FastAPI
In this article, we are going to see what is multiprocessing, and how multiprocessing can utilize the system resources efficiently and can reduce the time taken to complete a big task. We will see the "concurrent.futures" module that is used for multiprocessing in FastAPI and then see how we can use it to download a big zip file from the server eff
5 min read
Array in Python | Set 1 (Introduction and Functions)
Other than some generic containers like lists, Python in its definition can also handle containers with specified data types. The array can be handled in Python by a module named "array". They can be useful when we have to manipulate only specific data type values. Properties of ArraysEach array element is of the same data type and size. For exampl
7 min read
Complex Numbers in Python | Set 1 (Introduction)
Not only real numbers, Python can also handle complex numbers and its associated functions using the file "cmath". Complex numbers have their uses in many applications related to mathematics and python provides useful tools to handle and manipulate them. Converting real numbers to complex number An complex number is represented by " x + yi ". Pytho
5 min read
Django Introduction | Set 2 (Creating a Project)
Note- This article is in continuation of Django introduction. Popularity of Django Django is used in many popular sites like as: Disqus, Instagram, Knight Foundation, MacArthur Foundation, Mozilla, National Geographic etc. There are more than 5k online sites based on Django framework. ( Source ) Sites like Hot Frameworks assess the popularity of a
3 min read
Introduction to Simulation Modeling in Python
Simulation is imitating the operations which take place within a system to study its behavior. Analyzing and creating the model of a system to predict its performance is called simulation modeling. Simulation mimics a real-life process to determine or predict the response of the entire system. This helps to understand the dependency of each part of
4 min read
Introduction to Kivy ; A Cross-platform Python Framework
Kivy is an open-source, cross-platform Python framework used for developing multi-touch applications with a natural user interface. It allows developers to build applications that run on multiple platforms, including Windows, macOS, Linux, iOS, and Android. Kivy is based on the Model-View-Controller (MVC) architecture and uses a declarative languag
4 min read
Data Classes in Python | An Introduction
dataclass module is introduced in Python 3.7 as a utility tool to make structured classes specially for storing data. These classes hold certain properties and functions to deal specifically with the data and its representation.DataClasses in widely used Python3.6 Although the module was introduced in Python3.7, one can also use it in Python3.6 by
3 min read
Python | wxPython module Introduction
Python provides wxpython module which allows us to create high functional graphical user interface. It is an Open Source module, which means it is free for anyone to use and the source code is available for anyone to look and modify. It is implemented as a set of extension modules that wrap the GUI components of wxWidgets library which is written i
3 min read
Python | Introduction to PyQt5
There are so many options provided by Python to develop GUI application and PyQt5 is one of them. PyQt5 is cross-platform GUI toolkit, a set of python bindings for Qt v5. One can develop an interactive desktop application with so much ease because of the tools and simplicity provided by this library. A GUI application consists of Front-end and Back
3 min read
Python sorted containers | An Introduction
Sorted Containers is an Apache2 licensed sorted collections library, written in pure-Python, and fast as C-extensions. It was created by Grant Jenks and is an open source library. It is a collection of containers that allow us to insert and remove elements very efficiently while maintaining sorted order. Features: Pure-Python Fully documented Bench
6 min read
Introduction to pyglet library for game development in Python
Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc on Windows, Mac OS and Linux. This library is created purely in Python and it supports many features like windowing, user interface event handling, Joysticks, OpenGL graphics, loading images, and videos, and playing sounds and music.
2 min read
Introduction to Theory of Evolution in Python
The process of inheritance involves the transmission of characteristics from one generation to another in the form of genes. These genes actually have DNA which is the coded information about the characteristics. Due to inheritance, evolution takes place from one species to another. So we can conclude that evolution is a random process as it does n
2 min read
Introduction and Installation of Uberi/Speechrecognition in Python
One of the best library for speech recognition in Python and uses various engines and API to perform speech recognition online as well as offline. Installation Use this command in cmd or terminal make sure Python is installed and Python path is also stored in pc. pip install speechrecognition OR Download resources from PyPI and extract it in a fold
2 min read
Wand Python - Introduction and Installation
Imagemagick is a tool developed to convert images from one format to another. Due to a versatile range of image formats and its precise and simple working, it has a huge community support. We can get images from pdf files. Wand is a binding developed for python by Imagemagick.wWand opens and manipulate images. Wand provides a large number of functi
2 min read
pgmagick Python- Introduction and Installation
pgmagick is a GraphicsMagick binding for Python. This module provides methods for Image Editing and Manipulation. pgmagick is written by Hideo Hattori. We can do a lot of things using this library such as : Resize, rotate, sharpen, color reduce, or add special effects to an image. Create transparent image assets. Compare two images. Create a gradie
2 min read
Introduction to Sanic Web Framework - Python
WHAT IS SANIC? Sanic is an asynchronous web framework and web server for Python 3.5+ that’s written to go fast. Sanic was developed at MagicStack and is based on their uvloop event loop, which is a replacement for Python asyncio’s default event loop, thereby making Sanic blazing fast. Syntactically Sanic resembles Flask. Sanic maybe used as a repla
7 min read
PLY (Python lex-Yacc) - An Introduction
We all have heard of lex which is a tool that generates lexical analyzer which is then used to tokenify input streams and yacc which is a parser generator but there is a python implementation of these two tools in form of separate modules in a package called PLY. These modules are named lex.py and yacc.py and work similar to the original UNIX tools
3 min read
Introduction to SQLite in Python
Databases offer numerous functionalities by which one can manage large amounts of information easily over the web and high-volume data input and output over a typical file such as a text file. SQL is a query language and is very popular in databases. Many websites use MySQL. SQLite is a "light" version that works over syntax very much similar to SQ
3 min read
Introduction to Bokeh in Python
Bokeh is a Python interactive data visualization. Unlike Matplotlib and Seaborn, Bokeh renders its plots using HTML and JavaScript. It targets modern web browsers for presentation providing elegant, concise construction of novel graphics with high-performance interactivity. Features of Bokeh: Some of the important features of Bokeh are given below:
1 min read
Python Mahotas - Introduction
Mahotas is a computer vision and image processing and manipulation library for Python. A library is a collection of functions and methods that allows you to perform many actions without having to write hundreds of lines of code. Mahotas includes many algorithms that operates with arrays, mahotas currently has over 100 functions for image processing
2 min read
Introduction to Python for Absolute Beginners
Are you a beginner planning to start your career in the competitive world of Programming? Looking resources for Python as an Absolute Beginner? You are at the perfect place. This Python for Beginners page revolves around Step by Step tutorial for learning Python Programming language from very basics to advanced. Python is a high-level programming l
6 min read
Introduction to Chempy in Python
ChemPy is a python package designed mainly to solve problems in analytical, physical and inorganic Chemistry. It is a free, open-source Python toolkit for chemistry, chemical engineering, and materials science applications. ChemPy includes classes for representing substances, reactions, and systems of reactions. It also includes well-established fo
2 min read
Article Tags :
Practice Tags :