The Python organization has released the official version of Python 3.13, which includes many major changes.
One of the major changes we get is making GIL (Global Interpreter Lock) optional in Python 3.13.
In this article, you’ll see how to disable GIL in Python 3.13 to make multi-threaded programs faster.
Disable GIL in Python 3.13
First, download the official Python 3.13 on your local machine. Then proceed to install the Python executable file.
Follow the steps just as you install any Python version, you will see a step in which you are asked to choose the advanced installation options.
Now select the checkbox appearing at the end, this will install the different executable Python build with the name python3.13t
or python3.13t.exe
.
This will allow you to optionally disable or enable GIL in the runtime. Now proceed to install the setup.
After completing the setup for Python 3.13, if you look at the file location of Python 3.13, you will see that you also got a different Python build called python3.13t
.
If you remember that “free-threaded binaries” mode was marked “experimental”, this means that you don’t get GIL disabled by default.
But how do I disable GIL? Python organization provided a different CPython build which is also called “Free-threaded CPython”.
Free-threaded CPython will help you disable GIL. Let’s see how to do it.
Let’s say, you have a Python script and you want it to run with GIL disabled. You can use the following command.
python3.13t main.py
This CPython build comes with GIL disabled by default.
Practical
I have the following Python script (main.py
) that runs a multi-threaded task and calculates the time taken to complete the execution.
import sys
import sysconfig
import math
import time
import threading
def compute_factorial(n):
return math.factorial(n)
# Multi-threaded
def multi_threaded_compute(n):
threads = []
# Create 5 threads
for num in n:
thread = threading.Thread(target=compute_factorial, args=(num,))
threads.append(thread)
thread.start()
# Wait for all threads to complete
for thread in threads:
thread.join()
print("Factorial Computed.")
def main():
# Checking Version
print(f"Python version: {sys.version}")
# GIL Status
status = sysconfig.get_config_var("Py_GIL_DISABLED")
if status is None:
print("GIL cannot be disabled")
if status == 0:
print("GIL is active")
if status == 1:
print("GIL is disabled")
numlist = [100000, 200000, 300000, 400000, 500000]
# Multi-threaded Execution
start = time.time()
multi_threaded_compute(numlist)
end = time.time() - start
print(f"Time taken : {end:.2f} seconds")
if __name__ == "__main__":
main()
Now, we’ll run this script with and without free-threaded CPython.
With GIL enable (without free-threaded CPython)
python main.py
With GIL disable (with free-threaded CPython)
python3.13t main.py
That’s all for now.
Keep Coding✌✌
Top comments (0)