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
Fisherman is a free open source fishing bot written in python.

Fisherman is a free open source fishing bot written in python.

Pure | Cody 33 Jan 29, 2022
A Python 3 client for the beanstalkd work queue

Greenstalk Greenstalk is a small and unopinionated Python client library for communicating with the beanstalkd work queue. The API provided mostly map

Justin Mayhew 67 Dec 08, 2022
Toppr Os Auto Class Joiner

Toppr Os Auto Class Joiner Toppr os is a irritating platform to work with especially for students it takes a while and is problematic most of the time

1 Dec 18, 2021
Openfe - Alchemical free energy calculations for the masses

The Open Free Energy library Alchemical free energy calculations for the masses.

33 Dec 22, 2022
Interactive class notebooks for ECE4076 Computer Vision, weeks 1 - 6

ECE4076 Interactive class notebooks for ECE4076 Computer Vision, weeks 1 - 6. ECE4076 is a computer vision unit at Monash University, covering both cl

Michael Burke 9 Jun 16, 2022
A collection of online resources to help you on your Tech journey.

Everything Tech Resources & Projects About The Project Coming from an engineering background and looking to up skill yourself on a new field can be di

Mohamed A 396 Dec 31, 2022
GMHI: Gut Microbiome Health Index

GMHI: Gut Microbiome Health Index Description Gut Microbiome Health Index (GMHI)

Daniel Chang 2 Jun 30, 2022
A bot to use in a pump & dump event

A bot to use in a pump & dump event on Binance.com. Please note the bot is in heavy devleopment currently so be aware of errors. If you experience err

Freddie Jonas 189 Dec 24, 2022
A collection of simple tools that proved to be needed for hadling large periodic calculations with the VASP software package.

VESTA-tools A collection of simple tools that proved to be needed for handling large periodic calculations with the VASP software package. distTotCalc

Ilia Kichev 2 Dec 14, 2021
CaskDB is a disk-based, embedded, persistent, key-value store based on the Riak's bitcask paper, written in Python.

CaskDB - Disk based Log Structured Hash Table Store CaskDB is a disk-based, embedded, persistent, key-value store based on the Riak's bitcask paper, w

886 Dec 27, 2022
Write-ups for CTF Internacional MetaRed 2021 5th stage

MetaRed2021-5th-Writeups Write-ups for CTF Internacional MetaRed 2021 5th stage Easy (15) No Status Category Name Creator(s) 01 Done osint Cybersecuri

UA Cybersecurity 2 Dec 22, 2021
A python tool used for hacking WhatsApp by diverting otp

W-HACK A python tool used for hacking WhatsApp by diverting otp You can hack WhatsApp easily with this tool Note:OTP expires after 5 seconds HOW TO IN

Spider Anongreyhat 3 Oct 17, 2021
Configure request params such as text, color, size etc. And then download the image

Configure request params such as text, color, size etc. And then download the image

6 Aug 18, 2022
Hexa is an advanced browser.It can carry out all the functions present in a browser.

Hexa is an advanced browser.It can carry out all the functions present in a browser.It is coded in the language Python using the modules PyQt5 and sys mainly.It is gonna get developed more in the fut

1 Dec 10, 2021
Recreating my first CRUD in python, but now more professional

Recreating my first CRUD in python, but now more professional

Ricardo Deo Sipione Augusto 2 Nov 27, 2021
python scripts - mostly automation scripts

python python scripts - mostly automation scripts You can set your environment in various ways bash #!/bin/bash python - locally on remote host #!/bi

Enyi 1 Jan 05, 2022
About A python based Apple Quicktime protocol,you can record audio and video from real iOS devices

介绍 本应用程序使用 python 实现,可以通过 USB 连接 iOS 设备进行屏幕共享 高帧率(30〜60fps) 高画质 低延迟(200ms) 非侵入性 支持多设备并行 Mac OSX 安装 python =3.7 brew install libusb pkg-config 如需使用 g

YueC 124 Nov 30, 2022
Access Modbus RTU via API call to Sungrow WiNet-S

SungrowModbusWebClient Access Modbus RTU via API call to Sungrow WiNet-S Class based on pymodbus.ModbusTcpClient, completely interchangeable, just rep

8 Oct 30, 2022
You will need to install a few python packages for this one.

Features Bait support Auto repair will repair every 10 catches Anti detection (still a work in progress) but using random times and click positions Pr

12 Sep 21, 2022
Web UI for your scripts with execution management

Script-server is a Web UI for scripts. As an administrator, you add your existing scripts into Script server and other users would be ab

Iaroslav Shepilov 1.1k Jan 09, 2023