In this article, you will learn

  • Difference between Multi-Threading and MultiProcessing and when to use them
  • Implement MultiProcessing in Python using multiprocessing and concurrent.futures

What is MultiProcessing?

  • Multiprocessing allows you to spawn multiple processes within a program.
  • It allows you to leverage multiple CPU cores on your machine
  • Multiple processes within a program do not share the memory
  • Side steps the GIL(Global Interpreter Lock) limitation of Python which allows only one thread to hold control of the Python interpreter
  • Used for computation or CPU intensive programs

then what is Multi-threading and when to use it?

A Thread is the

  • Smallest set of independent commands executed in a program
  • Multiple threads within an application can execute simultaneously on a CPU referred to as MultiThreading
  • Runs always within a program and cannot run on its own
  • Used when programs ar network bound or there is heavy I/O operation
  • Memory is shared between multiple threads within a process and hence has lower resources consumption

Image for post

Below is the code to demonstrate that Multiprocessing does not share a memory, whereas Multi-Threading shares memory.

In the piece of code below, we check if the number passed in the list is a prime number or not. We will do this using both Multi-threading as well as using Multiprocessing

#python #developer

When and How to use MultiProcessing and Multi-Threading in Python
5.15 GEEK