About Python's multithreading and GIL

Overview

RELEASE THE GIL

===========================================================================

Python is a great language 😃 , but the GIL (Global Interpreter Lock) is a huge bottleneck 😢 . It's a lock that is held by the interpreter while executing any Python code. This means that if you have a bunch of Python threads running, they all will have to wait for the GIL to be released. This can be a problem, because the GIL is held for a long time, which can lead to many performance issues.

The GIL is released whenever a thread is ready to run, and it's held back until all threads are ready to run. This means that if you have a bunch of Python threads running, they'll all be waiting for the GIL to be released but they'll all be blocked still after release. So, even though the threads will run concurrently, only one thread will be allowed to run at the exact same time.

As you see, there are no way to get rid of the GIL from Python Interpreters.

You may ask, why Python intepreter has this GIL?

Ans: The main Python implementation(CPython) is written in C, and many C codes are not thread safe. Everything are objects in Python, garbage collection are done using reference counting. The big problem is if one thread(let's say first) that is tracing the reference count of an object, if any other thread(let's say second) deletes that same object, the first thread will have no idea that same object is deleted by other thread. That's because reference counting is always done by per thread basis. And also, there may be some situation if one thread may wait for some other threads which already finished its work, that's called deadlock. If all threads are accessing the same object and changing at the same time, it may lead to race condtions. To prevent deadlock or race conditions, there's some locks needed per thread basis which can protect their resources.

Note that, in Java or C#, garbage collection is done by tracing garbage collection, which are aware always of the threads, and provides atomicity.

What is the benefit of the GIL?

Ans: The following reasons are:

  1. It's easy to write C extensions in Python and provides better C API rather than many popular languages like Java or C#.
  2. GIL makes single threaded programs faster.
  3. CPython Interpreter loading time is faster than JVM loading time because of GIL.
  4. Developers don't have to worry about thread-safety, because GIL always provides thread safety.

But, the big question is: How can we get rid of the GIL for getting performance?

Ans: As a Python coder, you should always be aware of the performance you're getting from code, and the GIL. Although, there are multiple ways we can get rid of this. Those are:

  1. Using numpy arrays for fast computation or some other good libraries which provides C API.
  2. Using Cython or Numba, although Cython is preferred.
  3. Using OpenMP API for Python.
  4. Using Pybind11 if you are good enough to write C++ code.
  5. If you're not satisfied with all I've mentioned, you can write raw C code provided Python C API.

In this repo, you will see how to release the GIL using Cython.

Note that, Python functions are made in such a way, that those can release the GIL when it's I/O bound. Such as:

  1. While reading from a file, or writing to a file.
  2. While reading from a socket, or writing to a socket.
  3. While reading from a database, or writing to a database.
  4. While getting data from internet, or sending to a intenet.
  5. While sleeping for some time.

In those cases, for I/O bound tasks you can use threading module. And, for long running I/O bound tasks, it is recommended to use async/await(coroutines) syntax for better performance.

If don't need threads to run in parallel, you can use multiprocessing module. Running tasks in separate processes won't be any problem for the GIL because every process has their own interpreter, which are again locked by the GIL.

Which Python interpreter don't have the GIL?

Ans: Jython and IronPython don't have the GIL because they are implemented to run in JVM and .NET environment respectively. PyPy has the GIL but PyPy-STM(Software Transactional Memory) doesn't have the GIL.

References

You can know more about this topic which I mentioned below:

  1. Python's Infamous GIL - Larry Hastings
  2. The Gilectomy project - Larry Hastings
  3. Inside the Python GIL - David Beazley

Happy Coding with Python! 😊

Owner
Souvik Ghosh
A self-taught programmer 👨‍💻
Souvik Ghosh
Qt-creator-boost-debugging-helper - Qt Creator Debugging Helper for Boost Library

Go to Tools Options Debugger Locals & Expressions. Paste the script path t

Dmitry Bravikov 2 Apr 22, 2022
Strawberry Benchmark With Python

Strawberry benchmarks these benchmarks have been made to compare the performance of dataloaders and joined database queries. How to use You can run th

Doctor 4 Feb 23, 2022
Gunakan Dengan Bijak!!

YMBF Made with ❤️ by ikiwzXD_ menu Results notice me: if you get cp results, save 3/7 days then log in. Install script on Termux $ pkg update && pkg u

Ikiwz 0 Jul 11, 2022
The fundamentals of Python!

The fundamentals of Python Author: Mohamed NIANG, Staff ML Scientist Presentation This repository contains notebooks on the fundamentals of Python. Th

Mohamed NIANG 1 Mar 15, 2022
The fastest way to copy to (not from) high speed flash storage.

FastestCopy The fastest way to copy to (not from) high speed flash storage. This is about 3-6x faster than file copy on explorer.exe to usb flash driv

Derek Frombach 0 Nov 03, 2021
Notebooks for computing approximations to the prime counting function using Riemann's formula.

Notebooks for computing approximations to the prime counting function using Riemann's formula.

Tom White 2 Aug 02, 2022
The purpose is to have a fairly simple python assignment that introduces the basic features and tools of python

This repository contains the code for the python introduction lab. The purpose is to have a fairly simple python assignment that introduces the basic

1 Jan 24, 2022
Un script en python qui permet d'automatique bumpée (disboard.org) tout les 2h

auto-bumper Un script en python qui permet d'automatique bumpée (disboard.org) tout les 2h Pour la première utilisation, 1.Lancer Install.bat 2.(faire

!! 1 Jan 09, 2022
Exactly what it sounds like, which is something rad

EyeWitnessTheFitness External recon got ya down? That scan prevention system preventing you from enumerating web pages? Well look no further, I have t

Ellis Springe 18 Dec 31, 2022
Now you'll never be late for your Webinars or Meetings on the GoToWebinar Platform

GoToWebinar Launcher : Now you'll never be late for your Webinars or Meetings on the GoToWebinar Platform About Are you popular for always being late

Jay Thorat 6 Jun 07, 2022
Скрипт позволяет выгрузить участников чатов/каналов(по чату для комментариев) и сообщения в различные форматы файлов.

TG-Parser Парсер участников и сообщений из ТГ-Чатов и чатов для комментариев в ТГ-Каналах Возможности Выгрузка участников групп/каналов(по чату для ко

50 Jan 06, 2023
pyreports is a python library that allows you to create complex report from various sources

pyreports pyreports is a python library that allows you to create complex reports from various sources such as databases, text files, ldap, etc. and p

Matteo Guadrini aka GU 78 Dec 13, 2022
Shopify Backend Developer Intern Challenge - Summer 2022

Shopify Backend Developer Intern The task is build an inventory tracking web application for a logistics company. The detailed task details can be fou

Meet Gandhi 11 Oct 08, 2022
Enjoyable scripting experience with Python

Enjoyable scripting experience with Python

8 Jun 08, 2022
This repository contains the exercices for the robotics class at Supaero, 2022.

Supaero robotics, 2022 This repository contains the exercices for the robotics class at Supaero, 2022. The exercices are organized by notebook. Each n

Gepetto team, LAAS-CNRS 5 Aug 01, 2022
Plugin to manage site, circuit and device diagrams and documents in Netbox

Netbox Documents Plugin A plugin designed to faciliate the storage of site, circuit and device specific documents within NetBox Note: Netbox v3.2+ is

Jason Yates 38 Dec 24, 2022
A funny alarm clock I made in python

Wacky-Alarm-Clock Basically, I kept forgetting to take my medications, so I thought it would be a fun project to code my own alarm clock and make it r

1 Nov 18, 2021
ViberExport - Export messages from Viber messenger using viber.db file

📲 ViberExport Export messages from Viber messenger using viber.db file ⚡ Usage:

7 Nov 23, 2022
Домашние задания, выполненные на 3ем семестре РТУ МИРЭА, по дисциплине

ДЗ по курсу "Конфигурационное управление" в РТУ МИРЭА Описание В данном репозитории находятся домашние задания, выполненные на 3ем семестре РТУ МИРЭА,

Semyon Esaev 4 Dec 22, 2022
A timer for bird lovers, plays a random birdcall while displaying its image and info.

Birdcall Timer A timer for bird lovers. Siriema hatchling by Junior Peres Junior Background My partner needed a customizable timer for sitting and sta

Marcelo Sanches 1 Jul 08, 2022