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
Visual Python and C++ nanosecond profiler, logger, tests enabler

Look into Palanteer and get an omniscient view of your program Palanteer is a set of lean and efficient tools to improve the quality of software, for

Damien Feneyrou 1.9k Dec 26, 2022
JPMC Virtual Experience

This repository contains the submitted patch files along with raw files of the various tasks assigned by JPMorgan Chase & Co. through its Software Engineering Virtual Experience Program on Forage (fo

Vardhini K 1 Dec 05, 2021
☘️ Projet Voltaire Solver in Python3

☘️ Projet Voltaire Solver in Python3

Bidouffe 8 Dec 02, 2022
Drug Discovery App Using Lipinski's Rule-of-Five.

Drug Discovery App A Drug Discovery App Using Lipinski's Rule-of-Five. TAPIWA CHAMBOKO 🚀 About Me I'm a full stack developer experienced in deploying

tapiwa chamboko 3 Nov 08, 2022
HairCLIP: Design Your Hair by Text and Reference Image

Overview This repository hosts the official PyTorch implementation of the paper: "HairCLIP: Design Your Hair by Text and Reference Image". Our single

322 Dec 30, 2022
Backups made easy, automated, monitored and SECURED with an audited encryption

Backup Controller Backups made easy, automated, monitored and SECURED with an audited encryption. Schedules backup tasks executed by Backup Maker, upl

RiotKit 1 Jan 30, 2022
Reference python implementation of Chia pool operations for pool operators

This repository provides a sample server written in python, which is meant to server as a basis for a Chia Pool. While this is a fully functional implementation, it requires some work in scalability

Chia Network 451 Dec 13, 2022
A deployer and package manager for OceanBase open-source software.

OceanBase Deploy OceanBase Deploy (简称 OBD)是 OceanBase 开源软件的安装部署工具。OBD 同时也是包管理器,可以用来管理 OceanBase 所有的开源软件。本文介绍如何安装 OBD、使用 OBD 和 OBD 的命令。 安装 OBD 您可以使用以下方

OceanBase 59 Dec 27, 2022
Быстрый локальный старт

Быстрый локальный старт

Anton Ogorodnikov 1 Sep 28, 2021
A 100% python file organizer. Keep your computer always organized!

PythonOrganizer A 100% python file organizer. Keep your computer always organized! To run the project, just clone the folder and run the installation

3 Dec 02, 2022
A utility control surface for Ableton Live that makes the initialization of a Mixdown quick

Automate Mixdown initialization A script that transfers all the VSTs on your MIDI tracks to a new track so you can freeze your MIDI tracks and then co

Aarnav 0 Feb 23, 2022
Tool to generate wrappers for Linux libraries allowing for dlopen()ing them without writing any boilerplate

Dynload wrapper This program will generate a wrapper to make it easy to dlopen() shared objects on Linux without writing a ton of boilerplate code. Th

Hein-Pieter van Braam 25 Oct 24, 2022
Minimal, super readable string pattern matching for python.

simplematch Minimal, super readable string pattern matching for python. import simplematch simplematch.match("He* {planet}!", "Hello World!") {"p

Thomas Feldmann 147 Dec 01, 2022
Blender pluggin (python script) that adds a randomly generated tree with random branches and bend orientations

Blender pluggin (python script) that adds a randomly generated tree with random branches and bend orientations

Travis Gruber 2 Dec 24, 2021
Manually Install Python 2.7 pip without any problem !

Python2.7_install_pip Manually Install Python 2.7 pip without any problem ! Download installPip.py to your system and Run the code using this Command

Ali Jafari 1 Dec 09, 2021
Simulation simplifiée du fonctionnement du protocole RIP

ProjetRIPlay v2 Simulation simplifiée du fonctionnement du protocole RIP par Eric Buonocore le 18/01/2022 Sur la base de l'exercice 5 du sujet zéro du

Eric Buonocore 2 Feb 15, 2022
A library for pattern matching on symbolic expressions in Python.

MatchPy is a library for pattern matching on symbolic expressions in Python. Work in progress Installation MatchPy is available via PyPI, and

High-Performance and Automatic Computing 151 Dec 24, 2022
Connect Playground - easy way to fill in your account with production-like objects

Just set of scripts to initialise accpunt with production-like data: A - Basic Distributor Account Initialization INPUT Distributor Account Token ACTI

CloudBlue 5 Jun 25, 2021
Purge your likes and wall comments from VKontakte. Set yourself free from your digital footprint.

vk_liberator Regain liberty in the cruel social media world. This program assists you with purging your metadata from Russian social network VKontakte

20 Jun 11, 2021
Solutions to the language assignment for Internship in JALA Technologies.

Python Assignment Solutions (JALA Technologies) Solutions to the language assignment for Internship in JALA Technologies. Features Properly formatted

Samyak Jain 2 Jan 17, 2022