如下內容來自 維基 。 編程
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
舉例 ide
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) ui
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 。 spa