MULTITHREADING

Thread is a lightweight process or simply a subset of a process. It means running different tasks at the same time.

Why Multithreading is not possible in python?

Python is a single-threaded programming language. We cannot run any tasks parallelly at the same time. Global interpreter Lock(GIL) is a mechanism that restricts the running of multiple threads at the same time. Python is an interpreter language and it is implemented on CPython which supports the GIL mechanism. GIL mechanism allows us to run only one thread at the same time even if we have a core multi-core CPU. When two threads try to run at the same time One thread has to wait till running threads completion or any idle time of the running threads because the running thread acquires Global Interpreter Lock, When the lock gets released the next thread will start to run.

How multithreading is done in Python?

We can say, multithreading is an execution of different threads concurrently. In a single-core CPU, we can achieve multithreading by means of switching between the threads when there is an idle time or the CPU is waiting for IO operations. This switching operation is called context switching.

Output:

On the above program, What happens here is thread1 starts getting executed, when there is an idle time,thread2 will start getting executed. While shifting to the second thread each thread state can be saved and will be resumed from where the thread left off and vice versa. This will continue until the end of the program.

Pros of Multithreading:

  • It is much helpful in Input-Output operations.
  • Memory usage is very less in Multi-Threading.

    Cons of Multithreading:

  • Deadlock can occur.
  • Involving many threads can make the code complex to understand.

MULTIPROCESSING

Multiprocessing occurs in the system which has more than one processor. Python was developed at a time when people had no idea that there would be a computer with more than one processor. This paved the way for GIL when accessing python objects. Multiprocessing API helps us to run the process in more than one processor. Each process running in a different processor has its own one GIL and no deadlocks can occur.

Output:

In this, Each process will run on different processors. It will be like sharing work between colleagues. Each colleague will do their assigned job in their own way. Different process id in the output shows the process run in different processors.

Pros:

  • Work is done much faster in multiprocessing.
  • There is no GIL limitation since each process will have its own GIL
  • We can make use of multiple cores in the CPU.

Cons:

  • More memory will be taken by the program.