The Wayback Machine - https://web.archive.org/web/20240618093124/https://www.geeksforgeeks.org/understanding-fork-and-spawn-in-python-multiprocessing/
Open In App

Understanding ‘fork’ and ‘spawn’ in Python Multiprocessing

Last Updated : 06 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 creation of child processes but also offer control mechanisms for managing the flow of execution between parent and child processes.

Start Methods

A start method is a technique to start the child process in Python, There are 3 start methods

  • Fork: creates a copy from the existing process (resources used or altered by a parent will be referred by the child)
  • Spawn: creates the new process
  • Forkserver: new process from which future forked processes will be copied. (provides isolation and efficiency)

You can identify which technique was used as the start method by the multiprocessing module in Python by executing the following command:

Python3




import multiprocessing
print(multiprocessing.get_start_method())


Output

fork





You can set the desired start method type by following the snippet:

Python3




import multiprocessing
multiprocessing.set_start_method('spawn')


The type of start method used depends on the operating system, and some operating systems might not support certain start methods.

The following lists major OS Platforms and default start methods

  • Windows : spawn
  • macOS : spawn
  • Linux : Fork

As of now we focus on fork and spawn method

Fork

This fork method works on creating the exact clone or copy of the parent process. i.e resources utilised or altered by the parent process will be accessed by the child.

Screenshot-from-2023-08-19-11-35-42

For Example:

If you declare a global variable num and set its value to 10, then modify the value of this variable within the parent process before creating a child process. The child process after being forked, will inherit the updated value of num from the parent. In simpler terms, the child process receives a copy of the existing process, including any changes made on the resources in the fork method.

Explanation

The script initializes “num” as 10 globally, accessible to both the main and child processes. Main process updates it to 20, but child process inherits the modified value 20. The child process prints 20, increments it to 21. In the script showcased, the ‘fork’ method is used to create child processes that inherit a snapshot of the parent process’s memory, including variable values. However, changes made to shared variables within child processes don’t impact the parent process.

Python3




import multiprocessing
 
# initialize the value
num = 10
def childprocess():
   
    # refer to the global variable
    global num 
    print(f"In child process before update: {num}")
 
    #updating num value
    num+= 1
 
    print(f"In child process after update: {num}")
 
 
def mainprocess():
 
    # refer to the global variable
    global num
    print(f"In parent process before update {num}")
 
    #updating num value
    num = 20
 
    # execution logic
    print(f"In parent process after update: {num}")
    process = multiprocessing.Process(target = childprocess)
    process.start()
    process.join()
    print(f"At the end the vaule is: {num}")
 
if __name__ == '__main__':
   
    # setting start method as fork
    multiprocessing.set_start_method('fork')
    print(multiprocessing.get_start_method())
    mainprocess()


Output

fork
In parent process before update 10
In parent process after update: 20
In child process before update: 20
In child process after update: 21
At the end the vaule is: 20


Spawn

This spawn method works on creating new process from the parent process. i.e resources utilised or altered by the parent process will not get reflected in child process as we seen in fork mechanism.

Screenshot-from-2023-08-19-11-47-38

spawn start method

For Example:

If you declare a global variable num and set its value to 10, then modify the value of this variable within the parent process before creating a child process, the child process after being spawned will get access the value num as 10 and not the parent changed value 20. Means the spawn will tend to create a new fresh process and will not inherit the changes from parent.

Explanation

The script initializes “num” as 10 globally, accessible to both the main and child processes. Main process updates it to 20, but child process inherits the original 10. The child process prints 10, increments it to 11. In the script showcased, the ‘spawn’ method is employed to generate child processes, each equipped with an entirely fresh memory space. This method ensures that changes made to shared variables within child processes remain contained and do not affect the parent process.

Python3




import multiprocessing
 
# initialize the value
num = 10
def childprocess():
   
    # refer to the global variable
    global num 
    print(f"In child process before update: {num}")
 
    #updating num value
    num+= 1
 
    print(f"In child process after update: {num}")
 
 
def mainprocess():
     
    # refer to the global variable
    global num
    print(f"In parent process before update {num}")
 
    #updating num value
    num = 20
 
    # execution logic
    print(f"In parent process after update: {num}")
    process = multiprocessing.Process(target = childprocess)
    process.start()
    process.join()
    print(f"At the end the vaule is: {num}")
 
if __name__ == '__main__':
   
    # setting start method as spawn
    multiprocessing.set_start_method('spawn')
    print(multiprocessing.get_start_method())
    mainprocess()


Output

spawn
In parent process before update 10
In parent process after update: 20
In child process before update: 10
In child process after update: 11
At the end the vaule is: 20





Difference between Fork and Spawn methods.

Fork

Spawn

  • It is the default method used on Unix-like systems.
  • It creates child processes that inherit the entire memory space of the parent process, which can be memory-intensive.
  • Best suited for situations where you need to share a lot of data and state between the parent and child processes efficiently.
  • Use cases include parallelizing tasks with shared data or implementing multiprocessing on Unix-based systems.
  • It is the default method on Windows and is also available on Unix-like systems.
  • It creates child processes with a clean memory space, reducing the risk of memory-related issues and providing more isolation.
  • Suitable for scenarios where you want to avoid interference between parent and child processes and ensure safety and stability.
  • Use cases include running untrusted code, ensuring process isolation, and handling multiprocessing in a more controlled and secure manner.

Summary

  • Fork and spawn are entirely different mechanism for creating the new process
  • Fork inherits the changes done by the parent
  • Spawn will not inherit the changes done by the parent
  • In both fork and spawn changes made by the child process will not get reflected in parent. This is because the parent and child processes are distinct and independent entities after being spawned or forked


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
Run Python script from Node.js using child process spawn() method
Node.js is one of the most adopted web development technologies but it lacks support for machine learning, deep learning and artificial intelligence libraries. Luckily, Python supports all these and many more other features. Django Framework for Python can utilize this functionality of Python and can provide support for building new age web applica
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
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
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
Multiprocessing in Python | Set 1 (Introduction)
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 alloc
5 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 Multiprogramming, multitasking, multithreading and multiprocessing
Multiprogramming - Multiprogramming is known as keeping multiple programs in the main memory at the same time ready for execution.Multiprocessing - A computer using more than one CPU at a time.Multitasking - Multitasking is nothing but multiprogramming with a Round-robin scheduling algorithm.Multithreading is an extension of multitasking.FeatureMul
11 min read
Difference between Multiprocessing and Multithreading
Both Multiprocessing and Multithreading are used to increase the computing power of a system. Multiprocessing: Multiprocessing is a system that has more than one or two processors. In Multiprocessing, CPUs are added for increasing computing speed of the system. Because of Multiprocessing, There are many processes are executed simultaneously. Multip
1 min read
Practice Tags :