python - 为什么Python解释器不是线程安全的?

标签 python multithreading parallel-processing thread-safety gil

GIL 锁定核心,使线程无法并行运行。为什么会这样呢? 网上关于这方面的信息很少。

最佳答案

从非常基本的角度来说,GIL 可以阻止内存损坏,如果没有 GIL,多个线程可能会同时执行,从而导致不可预测的输出。

In CPython, the global interpreter lock, or GIL, is a mutex that protects access to Python objects, preventing multiple threads from executing Python bytecodes at once. This lock is necessary mainly because CPython's memory management is not thread-safe. (However, since the GIL exists, other features have grown to depend on the guarantees that it enforces.)

请参阅documentation

正如您将看到的,有些实现不使用 GIL,例如 Jython 和 IronPython。

还有一篇关于 Wikipedia that deals with this topic. 的非常有用的文章

A global interpreter lock (GIL) is a mutual-exclusion lock held by a programming language interpreter thread to avoid sharing code that is not thread-safe with other threads. In implementations with a GIL, there is always one GIL for each interpreter process.

关于python - 为什么Python解释器不是线程安全的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49090416/

相关文章:

python - 在python之前,声音已经完成了吗?

python - 来自托盘图标的弹出窗口在窗口关闭时不会关闭程序

python异步线程异常处理

.net-3.5 - .NET 3.5 上的并行 - 线程未在嵌套中完成任务

algorithm - 如何为这个调度和资源分配问题建模

java - java 8何时将并行流组合在一起?

python - OSX 10.11 上的 Headless Selenium + Xvfb + Chrome

python - Matplotlib 按 Y 值绘制散点图颜色

multithreading - 使用QTcpServer/QTcpSocket管理来自单个客户端的并发请求

使用线程并发下载文件