【原创】什么是 GIL(Global Interpreter Lock)

  1. 云栖社区>
  2. 博客>
  3. 正文

【原创】什么是 GIL(Global Interpreter Lock)

摩云飞 2016-05-11 14:13:15 浏览1169
展开阅读全文


以下内容来自 维基 。

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 languages with a GIL, there is always one GIL for each interpreter  process .  CPython  and  CRuby  use GILs.
全局解释器锁(GIL)是一种互斥锁,由程序语言解析线程持有,用于避免代码共享可能导致的线程安全问题。在支持GIL的语言中,每一个解释器进程中都会含有一个GIL。其中 CPython 和 CRubu 都支持 GIL 。

Applications written in programming languages with a GIL can be designed to use separate processes to achieve full parallelism, as each process has its own interpreter and in turn has its own GIL. Otherwise, the GIL can be a significant barrier to parallelism—a price paid for having the dynamism of the language.
使用支持 GIL 的编程语言写的应用程序能够同时使用不同的进程并行完成工作,因为每一个进程都拥有自己的解释器,也即拥有自己的 GIL 。否则,GIL会陈伟并行执行的瓶颈 -- 无法获得语言的“动态”特性。


Benefits and drawbacks
优点和缺点

Use of a Global Interpreter Lock in a language effectively limits the amount of parallelism reachable through concurrency of a single interpreter process with multiple threads. If the process is almost purely made up of interpreted code and does not make calls outside of the interpreter for long periods of time (which can release the lock on the GIL on that thread while it processes), there is likely to be very little increase in speed when running the process on a multiprocessor machine. Due to signaling with a CPU-bound thread, it can cause a significant slowdown, even on single processors.[1]
在语言中使用 GIL 能够有效限制单一解释器进程(内部含有多线程)的并发度。如果该进程几乎完全由带解释代码构成,且不会长时间调用解释器外的东东(长时间调用可能会导致在调用线程上释放掉 GIL 的锁),那么几乎不会发现在多处理器机器上运行进行时速度上的略微增长。

Reasons for employing such a lock include: 
increased speed of single-threaded programs (no necessity to acquire or release locks on all data structures separately) 
easy integration of C libraries that usually are not thread-safe. 
ease of implementation (having a single GIL lock is much simpler to implement than a lock free interpreter or one using fine grained locks). 
使用这种锁的原因包括以下几个方面:
可以增加单线程程序的运行速度(不再需要对所有数据结构分别获取或释放锁)
容易和通常非线程安全的 C 库进行集成
容易实现(使用单独的 GIL 锁要比实现无锁,或者细粒度锁的解释器更容易)

Examples
举例

Some language implementations that implement a Global Interpreter Lock are CPython, the most widely used implementation of Python,[2][3] and Ruby MRI, the reference implementation of Ruby (where it is called Global VM Lock). 
一些支持 GIL 的语言的实现包括 CPython(Python 语言最被广泛使用的一种实现),Ruby MRI(Ruby 的推荐实现,GIL 在 Ruby 中被称为 Global VM Lock)

JVM-based equivalents of these languages (Jython and JRuby) do not use Global Interpreter Locks. IronPython and IronRuby are implemented on top ofMicrosoft's Dynamic Language Runtime and also avoid using a GIL.[4]
基于 JVM 的上述语言的等价实现(Jython 和 JRuby)不使用 GIL。IronPython 和 IronRuby 被实现成微软的动态语言运行时,并在其中避免使用 GIL 。

 

网友评论

登录后评论
0/500
评论
摩云飞
+ 关注