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
JD扫码获取Cookie 本地版

JD扫码获取Cookie 本地版 请无视手机上的提示升级京东版本的提示! 下载链接 https://github.com/Zy143L/jd_cookie/releases 使用Python实现 代码很烂 没有做任何异常捕捉 但是能用 请不要将获取到的Cookie发送给任何陌生人 如果打开闪退 请使

Zy143L 420 Dec 11, 2022
Coffeematcher is a python library to randomly match participants for coffee meetings.

coffeematcher coffeematcher is a python library to randomly match participants for coffee meetings. Installation Clone the repository: git clone https

Thomas Wesselink 3 May 06, 2022
One Ansible Module for using LINE notify API to send notification. It can be required in the collection list.

Ansible Collection - hazel_shen.line_notify Documentation for the collection. ansible-galaxy collection install hazel_shen.line_notify --ignore-certs

Hazel Shen 4 Jul 19, 2021
Archive, organize, and watch for changes to publicly available information.

0. Overview The Trapper Keeper is a collection of scripts that support archiving information from around the web to make it easier to study and use. I

Bill Fitzgerald 9 Oct 26, 2022
Repository for my Monika Assistant project

Monika_Assistant Repository for my Monika Assistant project Major changes: Added face tracker Added manual daily log to see how long it takes me to fi

3 Jan 10, 2022
A Python feed reader library.

reader is a Python feed reader library. It aims to allow writing feed reader applications without any business code, and without enforcing a dependenc

266 Dec 30, 2022
Homed - Light-weight, easily configurable, dockerized homepage

homed GitHub Repo Docker Hub homed is a light-weight customizable portal primari

Matt Walters 12 Dec 15, 2022
Shell scripts made simple 🐚

zxpy Shell scripts made simple 🐚 Inspired by Google's zx, but made much simpler and more accessible using Python. Rationale Bash is cool, and it's ex

Tushar Sadhwani 492 Dec 27, 2022
An example project which contains the Unity components necessary to complete Navigation2's SLAM tutorial with a Turtlebot3, using a custom Unity environment in place of Gazebo.

Navigation 2 SLAM Example This example provides a Unity Project and a colcon workspace that, when used together, allows a user to substitute Unity as

Unity Technologies 183 Jan 04, 2023
Terrible python code from the "bubble that breaks maths" video.

Terrible python code from the "bubble that breaks maths" video.

Stand-up Maths 12 Oct 25, 2022
msImpersonate - User account impersonation written in pure Python3

msImpersonate v1.0 msImpersonate is a Python-native user impersonation tool that is capable of impersonating local or network user accounts with valid

Joe Helle 90 Dec 16, 2022
Script for resizing MTD partitions on a QNAP device in order to be available to upgrade from buster to bullseye

QNAP partitions resize for kirkwood devices. As explained by Marin Michlmayr, Debian bullseye support on kirkwood QNAP devices was dropped due to [mai

Arnaud Mouiche 26 Jan 05, 2023
Check bookings for TUM libraries.

TUM Library Checker Only for educational purposes This repository contains a crawler to save bookings for TUM libraries in a CSV file. Sample data fro

Leon Blumenthal 3 Jan 27, 2022
A Python version of Canvacord

A copy of canvacord made in python! Installation Run any of these commands in terminal: Mac / Linux pip install canvacord Windows python -m pip insta

10 Mar 28, 2022
Course materials for a 3-day seminar "Machine Learning and NLP: Advances and Applications" at New College of Florida

Machine Learning and NLP: Advances and Applications This repository hosts the course materials used for a 3-day seminar "Machine Learning and NLP: Adv

Yoshi Suhara 11 Jun 22, 2022
Let's pretend you want to create a AWS Lambda project called "sns-processor".

Usage Let's pretend you want to create a AWS Lambda project called "sns-processor". Rather than using lambda and then editing the results to include y

1 Dec 31, 2021
Convert Beat Saber maps to Tesla light shows!

Tesla x Beat Saber - Light Show Converter Convert Beat Saber maps to Tesla light shows! This project requires FFMPEG and all packages from requirement

HLVM 20 Dec 21, 2022
Procedural 3D data generation pipeline for architecture

Synthetic Dataset Generator Authors: Stanislava Fedorova Alberto Tono Meher Shashwat Nigam Jiayao Zhang Amirhossein Ahmadnia Cecilia bolognesi Dominik

Computational Design Institute 49 Nov 25, 2022
JurjenLang, an interpreted programming language

JurjenLang An interpreted programming language Getting started Follow these three steps on your computer to get started git clone https://github.com/J

JVerbruggen 5 May 03, 2022
AutoMetamon: Simple program to play Metamon automatically

AutoMetamon: Simple program to play Metamon automatically

Ngô Văn Tuấn 2 Sep 13, 2022