为什么要使用全局翻译锁? [英] Why the Global Interpreter Lock?

查看:93
本文介绍了为什么要使用全局翻译锁?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python的Global Interpreter Lock的确切功能是什么? 其他编译为字节码的语言是否采用类似的机制?

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 can execute in parallel when they don't share any resources. However there is a much larger administrative overhead. For every 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 machines due to lock contention.

其他编译为字节码的语言是否采用类似的机制?

Do other languages that are compiled to bytecode employ a similar mechanism?

它有所不同,可能不应该将它视为语言属性,而应该将其视为实现属性. 例如,有些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.

这篇关于为什么要使用全局翻译锁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆