GIL 在 Python 3.13 中成为可选

1次阅读

共计 1262 个字符,预计需要花费 4 分钟才能阅读完成。

与 Python 3.12 相比,Python 3.13 带来了主要的新功能,其中之一是自由线程模式,它禁用全局解释器锁,允许线程更多地并发运行。

这是一个实验性功能,如果您想尝试一下,可以从这里下载 Python 3.13 的测试版:https://www.python.org/downloads/release/python-3130b3/

当您使用 –disable-gil 选项配置 Python 时,GIL 将被禁用,该选项只不过是安装时的构建配置(自由线程构建)。这将允许使用环境变量 PYTHON_GIL 选择性地启用和禁用 GIL,该变量可以分别设置为 1 和 0。
它还将提供命令行选项 -X gil,也可以将其设置为 0(禁用)和 1(启用):

v3.13

GIL disabled

python3 -X gil=0 sample.py

GIL enabled

python3 -X gil=1 sample.py

单线程和多线程之间的差异并不大,但在多进程任务的情况下我们可以看到相当大的差异。
使用 Python v3.12,GIL 运行 gil.py

python gil.py
Python version: 3.12.2 (tags/v3.12.2:6abddd9, Feb  6 2024, 21:26:36) [MSC v.1937 64 bit (AMD64)]
GIL cannot be disabled
Single-threaded: Factorial Computed.
Single-threaded time taken: 9.04 seconds
Multi-threaded: Factorial Computed.
Multi-threaded time taken : 8.21 seconds
Multi-process: Factorial Computed.
Multi-process time taken  : 5.64 seconds

Python 3.13 在没有 GIL 的情况下运行 gil.py

D:/SACHIN/Python13/python3.13t gil.py
Python version: 3.13.0b3 experimental free-threading build (tags/v3.13.0b3:7b41395, Jun 27 2024, 16:17:17) [MSC v.1940 64 bit (AMD64)]
GIL is disabled
Single-threaded: Factorial Computed.
Single-threaded time taken: 9.28 seconds
Multi-threaded: Factorial Computed.
Multi-threaded time taken : 4.86 seconds
Multi-process: Factorial Computed.
Multi-process time taken  : 6.14 seconds

可以看到,Multi-threaded 多进程任务的情况下我们可以看到相当大的性能差异。

Ref https://geekpython.in/gil-become-optional-in-python

正文完
 0