天天看點

【原創】什麼是 GIL(Global Interpreter Lock)

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 。