python - 关于python GIL的一个概念性问题,它实际上意味着什么

标签 python gil

我怀疑类似的问题可能已经被问过多次。
但我很难得到我的问题的答案..


我知道 GIL 使得一次只能执行单个 python 线程。
(我的理解来自https://dabeaz.com/python/UnderstandingGIL.pdf)

但如果我仔细想想,拥有 GIL 基本上与单核环境具有相同的效果。
有了 Gil,Python 多线程就可以在一个核心中运行。

作为一名程序员,我仍然必须处理所有可能发生的竞争条件。
还是目的不是为了我?这是关于 python 解释器安全吗?

我想这个问题可以改写为,如果 python 删除 GIL,用户程序会受到什么影响?

我的理解是,

if GIL is gone, 
it will make python multithreading: 
single core thread programming -> multi core thread programming

或者还有其他事情发生吗?
(如果我的理解没错的话,GIL是我们其实可以拿出来的。我的意思是如果能做到的话,就可以在不影响用户程序的情况下做到)

我想我必须强调,这里我只对用户程序的角度感兴趣。 (GIL如何影响python运行时(解释器)不是我在这里问的)

最佳答案

首先,请了解并非所有 Python 实现都有 GIL,例如 Jython 和 IronPython。然而,大多数人使用的主要 CPython 确实有一个。

需要注意的一件事是,CPython 已尝试删除 GIL,但这确实很难,因为所有构建的内容都假设 GIL 存在。 PyPy FAQ 中描述了删除 GIL 所涉及的一些问题的快速而简单的概述。 (PyPy 也有一个 GIL):

Yes, PyPy has a GIL. Removing the GIL is very hard. On top of CPython, you have two problems: (1) GC, in this case reference counting; (2) the whole Python language.

For PyPy, the hard issue is (2): by that I mean issues like what occurs if a mutable object is changed from one thread and read from another concurrently. This is a problem for any mutable type: it needs careful review and fixes (fine-grained locks, mostly) through the whole Python interpreter. It is a major effort, although not completely impossible, as Jython/IronPython showed. This includes subtle decisions about whether some effects are ok or not for the user (i.e. the Python programmer).

CPython has additionally the problem (1) of reference counting. With PyPy, this sub-problem is simpler: we need to make our GC multithread-aware. This is easier to do efficiently in PyPy than in CPython. It doesn’t solve the issue (2), though.

Note that there was work to support a Software Transactional Memory (STM) version of PyPy. This should give an alternative PyPy which works without a GIL, while at the same time continuing to give the Python programmer the complete illusion of having one. This work is currently a bit stalled because of its own technical difficulties.

所有这些都来自一群正在构建自己的全新编译器的开发人员。想象一下 CPython 小组需要处理的所有问题,该小组规模更大,也需要确保一定程度的向后兼容性。

所以,是的,您的猜测是正确的:这并不全与您有关。如果有人能够弄清楚如何取出 GIL 而不弄乱一堆其他东西,那么它可能会被 CPython 合并。它会让 Python 代码更快,并且对于那些期待线程通常如何工作的人来说不会那么困惑。但目前还没有人能够做得足够好。从我读到的内容来看,它慢慢地不再是一个“我们应该解决的问题”,而更像是一个“我们必须处理的问题”。

关于python - 关于python GIL的一个概念性问题,它实际上意味着什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76550436/

相关文章:

python - 如何在组内逐条查找唯一值?

python - 在 python 中线程化 c++ 程序

python - Python 3.2 及更高版本中的 sys.setswitchinterval

python - 从 C 调用 python 函数作为回调。处理 GIL 的正确方法是什么?

python - 在后台线程 python/pygtk 中运行计算

python - 按 id 过滤 Tensorflow 数据集

python - 为 Pandas DataFrame 图设置 xlim

python - 从两个列表中提取相同的元素

cython - 一些标准的 C 库数学运算与 noGIL 不兼容

python - PythonAnywhere 上带有 Web.py 的 Web 表单