问题描述
Python 的全局解释器锁的作用究竟是什么?其他编译为字节码的语言是否采用类似的机制?
What is exactly the function of Python's Global Interpreter Lock?Do other languages that are compiled to bytecode employ a similar mechanism?
推荐答案
一般来说,对于任何线程安全问题,您都需要使用锁来保护内部数据结构.这可以通过不同的粒度级别来完成.
In general, for any thread safety problem you will need to protect your internal data structures with locks.This can be done with various levels of granularity.
您可以使用细粒度锁,其中每个单独的结构都有自己的锁.
You can use fine-grained locking, where every separate structure has its own lock.
您可以使用粗粒度锁,其中一个锁可以保护一切(GIL 方法).
You can use coarse-grained locking where one lock protects everything (the GIL approach).
每种方法各有利弊.细粒度锁定允许更大的并行度 - 两个线程可以当它们不共享任何资源时并行执行.但是,管理开销要大得多.为了每一行代码,你可能需要获取和释放几个锁.
There are various pros and cons of each method. Fine-grained locking allows greater parallelism - two threads canexecute in parallel when they don't share any resources. However there is a much larger administrative overhead. Forevery line of code, you may need to acquire and release several locks.
粗粒度的方法正好相反.两个线程不能同时运行,但一个单独的线程会运行得更快,因为它没有做太多的簿记.最终归结为单线程速度和并行性之间的权衡.
The coarse grained approach is the opposite. Two threads can't run at the same time, but an individual thread will run faster because its not doing so much bookkeeping. Ultimately it comes down to a tradeoff between single-threaded speed and parallelism.
已经有一些尝试在python中删除GIL,但是单线程机器的额外开销通常太大.即使在多处理器机器上,某些情况实际上可能会更慢由于锁争用.
There have been a few attempts to remove the GIL in python, but the extra overhead for single threaded machines was generally too large. Some cases can actually be slower even on multi-processor machinesdue to lock contention.
其他编译为字节码的语言是否采用类似的机制?
它各不相同,它可能不应该被视为一种语言属性,而是一种实现属性.例如,有一些 Python 实现,例如 Jython 和 IronPython,它们使用其底层 VM 的线程方法,而不是 GIL 方法.此外,Ruby 的下一版本看起来将向引入一个 GIL.
It varies, and it probably shouldn't be considered a language property so much as an implementation property.For instance, there are Python implementations such as Jython and IronPython which use the threading approach of their underlying VM, rather than a GIL approach. Additionally, the next version of Ruby looks to be moving towards introducing a GIL.
这篇关于为什么全局解释器锁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!