> For the complete documentation index, see [llms.txt](https://docs.xiwind-corp.com/tech/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.xiwind-corp.com/tech/python/gil-quan-yu-zhi-yi-qi-suo.md).

# GIL 【全域直譯器鎖】

## GIL

***

單個 Python processes 中的多個 thread 之間可能存在競爭條件，可能會導致意外行為和數據損壞。因此，Python 直譯器使用 GIL 來使 Pytho 執行的指令(稱為 Python bytecode) 的線程安全。

<figure><img src="/files/9Wab97nRq9bqM2jYJNrX" alt="Python processes"><figcaption><p>Python processes</p></figcaption></figure>

GIL 的作用是，每當 Python 程序中的 thread 要運行時，它必須先獲取鎖才能執行。 對於大多數具有單個 thread（稱為主要 thread）的 Python 程序而言，這不是問題。

GIL (Global Interpreter Lock，全域解釋器鎖，全域直譯器鎖) 是 CPython 直譯器中使用的一種機制，它是 Python 的預設實現。 此鎖確保一次只有一個 thread 執行 Python bytecode，即使在多核心設備上也是如此。 這意味著在一個多 thread 的 Python 程序中，由於 GIL 的存在，它們無法同時充分利用多個 CPU 內核。

然而，Python 中的某些操作可以釋放 GIL，允許多個 thread concurrently 執行 Python bytecode，並利用多個 CPU 內核。 這些操作通常涉及在外部 library 中實現的計算密集型任務，這些任務通常使用 C 或 C++ 等語言編寫並繞過 GIL。下面是幾個可以釋放 GIL 的情景：

* **使用外部 library** ：例如：用於數值計算的 NumPy 或用於數據處理的 Pandas。 這些 library 在內部管理自己的 concurrency，並且可以利用多個 CPU 核心。
* **I/O-bound 任務**：涉及 I/O 操作的任務。例如：讀取或寫入檔案、發出網路請求、interacting library。 這些任務通常大部分時間都在等待 I/O 操作完成，在此期間 GIL 會自動釋放，允許其他 thread 執行。
* **multiprocessing module**：允許執行多個 processes，允許充分利用多個 CPU 核心。每個 processes 都有獨立的直譯器、 memory、GIL。

雖然使用外部 library、執行 I/O 操作、 CPU 綁定任務能繞過繞過 GIL，但 Python bytecode 執行仍將受到 GIL 的限制，不能充分利用多個 CPU 內核，即使在 `ThreadPoolExecutor` 中執行也是如此。但是，這並不意味著你不能在多 CPU 機器上用好 Python。 您只需要將工作分配給多個 processes 而不是多個 thread。

幸運的是，許多潛在的阻塞或長時間運行的操作，都發生在 GIL 之外。例如：I/O 操左、Image Processing 和 NumPy 運算， 因此，只有在花費大量時間在解釋 CPython bytecode 的 multithreaded 程序中，GIL 才會成為瓶頸。

{% hint style="info" %}
在 Cython 中，可以使用 `with` 語句暫時釋放 GIL。其他規則詳見：[GlobalInterpreterLock - Python Wiki](https://wiki.python.org/moin/GlobalInterpreterLock)
{% endhint %}

### Python 3.13 GIL 變為可選選項

***

[Python-3.12 告別 GIL 鎖 & 性能原地飛升！-騰訊雲開發者社區-騰訊雲](https://cloud.tencent.com/developer/article/2219746)

[PEP 703 – 在 CPython 中使全局解釋器鎖可選 | peps.python.org](https://peps.python.org/pep-0703/)

## 參考資料

***

[Library and Extension FAQ — Python 3.11.4 documentation](https://docs.python.org/3/faq/library.html#id18)

[ThreadPoolExecutor vs. the Global Interpreter Lock (GIL)](https://superfastpython.com/threadpoolexecutor-vs-gil/)

[GlobalInterpreterLock - Python Wiki](https://wiki.python.org/moin/GlobalInterpreterLock)

[Day4：Coroutine 的四大特點 - iT 邦幫忙::一起幫忙解決難題，拯救 IT 人的一天](https://ithelp.ithome.com.tw/articles/10261501)
