哈嘍大家好,我是鹹魚 幾天前,IBM 工程師 Martin Heinz 發文表示 python 3.12 版本回引入"Per-Interpreter GIL”,有了這個 Per-Interpreter 全局解釋器鎖,python 就能實現真正意義上的並行/併發 我們知道,python 的多線程/進程 ...
哈嘍大家好,我是鹹魚
幾天前,IBM 工程師 Martin Heinz 發文表示 python 3.12 版本回引入"Per-Interpreter GIL”,有了這個 Per-Interpreter 全局解釋器鎖,python 就能實現真正意義上的並行/併發
我們知道,python 的多線程/進程並不是真正意義上的多線程/進程,這是因為 python GIL (Global Interpreter Lock)導致的
而即將發佈的 Python 3.12 中引入了名為 "Per-Interpreter GIL" 的新特性,能夠實現真正的併發
接下來我們來看下這篇文章,原文鏈接如下:
https://martinheinz.dev/blog/97
譯文
Python 到現在已經 32 歲了,但它到現在還沒有實現適當的、真正的併發/並行
由於將在 Python 3.12 (預計 2023 年 10 月發佈)中引入 “Per-Interpreter GIL”(全局解釋器鎖),這種情況將會被改變
雖然距離 python 3.12 的發佈還有幾個月的時間,但是相關代碼已經實現了。所以讓我們提前來瞭解一下如何使用子解釋器 API(ub-interpreters API) 來編寫出真正的併發Python代碼
子解釋器(Sub-Interpreters)
我們首先來看下這個 “Per-Interpreter GIL” 是如何解決 Python 缺失適當併發性這個問題的
簡單來講,GIL(全局解釋器鎖)是一個互斥鎖,它只允許一個線程式控制制 Python 解釋器(某個線程想要執行,必須要先拿到 GIL ,在一個 python 解釋器裡面,GIL 只有一個,拿不到 GIL 的就不允許執行)
這就意味著即使你在 Python 中創建多個線程,也只會有一個線程在運行
隨著 “Per-Interpreter GIL” 的引用,單個 python 解釋器不再共用同一個 GIL。這種隔離級別允許每個子 python 解釋器真正地併發運行
這意味著我們可以通過生成額外的子解釋器來繞過 Python 的併發限制,其中每個子解釋器都有自己的GIL(拿到一個 GIL 鎖)
更詳細的說明請參見 PEP 684,該文檔描述了此功能/更改:https://peps.python.org/pep-0684/#per-interpreter-state
如何安裝
想要使用這個新功能,我們需要安裝最新的 python 版本,這需要源碼編譯安裝
# https://devguide.python.org/getting-started/setup-building/#unix-compiling
git clone https://github.com/python/cpython.git
cd cpython
./configure --enable-optimizations --prefix=$(pwd)/python-3.12
make -s -j2
./python
# Python 3.12.0a7+ (heads/main:22f3425c3d, May 10 2023, 12:52:07) [GCC 11.3.0] on linux
# Type "help", "copyright", "credits" or "license" for more information.
C-API 在哪裡
現在我們已經安裝好了最新版本,那麼我們該如何使用子解釋器呢?我們可以直接通過 import
來導入嗎?不幸的是,還不能
正如 PEP-684 中指出的: ...this is an advanced feature meant for a narrow set of users of the C-API.
Per-Interpreter GIL 的特性目前只能通過 C-API 使用,還沒有直接的介面供開發人員使用
介面預計會在 PEP 554中出現,如果大家能夠接受,它應該會在 Python 3.13 中出現,在這個版本出現之前,我們必須自己想辦法來實現子解釋器
雖然還沒有相關文檔,也沒有相關模塊可以導入,但 CPython 代碼庫中有一些代碼段向我們展示瞭如何使用它:
- 方法一:我們可以使用
_xxsubinterpreters
模塊(因為是通過 C 實現的,所以命名比較奇怪,而且在 python 中不能夠簡單地去檢查代碼) - 方法二:可以使用 CPython 的 test 模塊,該模塊具有用於測試的示例 Interpreter(和 Channel)類
# Choose one of these:
import _xxsubinterpreters as interpreters
from test.support import interpreters
通常情況下我們一般用上面的第二種方法來實現
我們已經找到了子解釋器,但我們還需要通過 test 模塊去借用一些輔助函數,以便將代碼傳遞給子解釋器,輔助函數如下
from textwrap import dedent
import os
# https://github.com/python/cpython/blob/
# 15665d896bae9c3d8b60bd7210ac1b7dc533b093/Lib/test/test__xxsubinterpreters.py#L75
def _captured_script(script):
r, w = os.pipe()
indented = script.replace('\n', '\n ')
wrapped = dedent(f"""
import contextlib
with open({w}, 'w', encoding="utf-8") as spipe:
with contextlib.redirect_stdout(spipe):
{indented}
""")
return wrapped, open(r, encoding="utf-8")
def _run_output(interp, request, channels=None):
script, rpipe = _captured_script(request)
with rpipe:
interp.run(script, channels=channels)
return rpipe.read()
將 interpreters
模塊與上面的輔助函數組合在一起,便可以生成第一個子解釋器:
from test.support import interpreters
main = interpreters.get_main()
print(f"Main interpreter ID: {main}")
# Main interpreter ID: Interpreter(id=0, isolated=None)
interp = interpreters.create()
print(f"Sub-interpreter: {interp}")
# Sub-interpreter: Interpreter(id=1, isolated=True)
# https://github.com/python/cpython/blob/
# 15665d896bae9c3d8b60bd7210ac1b7dc533b093/Lib/test/test__xxsubinterpreters.py#L236
code = dedent("""
from test.support import interpreters
cur = interpreters.get_current()
print(cur.id)
""")
out = _run_output(interp, code)
print(f"All Interpreters: {interpreters.list_all()}")
# All Interpreters: [Interpreter(id=0, isolated=None), Interpreter(id=1, isolated=None)]
print(f"Output: {out}") # Result of 'print(cur.id)'
# Output: 1
生成和運行新解釋器的一種方法是使用 create()
函數,然後將解釋器與我們想要執行的代碼一起傳遞給 _run_output()
輔助函數
還有一種更簡單的方法,如下所示
interp = interpreters.create()
interp.run(code)
直接使用 interpreters
模塊的 run
方法。
但如果我們運行上面這兩段代碼時,會收到以下報錯
Fatal Python error: PyInterpreterState_Delete: remaining subinterpreters
Python runtime state: finalizing (tstate=0x000055b5926bf398)
為了避免這個報錯,我們還需要清理一些懸掛的解釋器:
def cleanup_interpreters():
for i in interpreters.list_all():
if i.id == 0: # main
continue
try:
print(f"Cleaning up interpreter: {i}")
i.close()
except RuntimeError:
pass # already destroyed
cleanup_interpreters()
# Cleaning up interpreter: Interpreter(id=1, isolated=None)
# Cleaning up interpreter: Interpreter(id=2, isolated=None)
線程
雖然使用上面的輔助函數運行代碼是可行的,但在 threading
模塊中使用熟悉的介面可能會更方便
import threading
def run_in_thread():
t = threading.Thread(target=interpreters.create)
print(t)
t.start()
print(t)
t.join()
print(t)
run_in_thread()
run_in_thread()
# <Thread(Thread-1 (create), initial)>
# <Thread(Thread-1 (create), started 139772371633728)>
# <Thread(Thread-1 (create), stopped 139772371633728)>
# <Thread(Thread-2 (create), initial)>
# <Thread(Thread-2 (create), started 139772371633728)>
# <Thread(Thread-2 (create), stopped 139772371633728)>
我們通過把 interpreters.create
函數傳遞給Thread
,它會自動線上程內部生成新的子解釋器
我們也可以結合這兩種方法,並將輔助函數傳遞給 threading.Thread
:
import time
def run_in_thread():
interp = interpreters.create(isolated=True)
t = threading.Thread(target=_run_output, args=(interp, dedent("""
import _xxsubinterpreters as _interpreters
cur = _interpreters.get_current()
import time
time.sleep(2)
# Can't print from here, won't bubble-up to main interpreter
assert isinstance(cur, _interpreters.InterpreterID)
""")))
print(f"Created Thread: {t}")
t.start()
return t
t1 = run_in_thread()
print(f"First running Thread: {t1}")
t2 = run_in_thread()
print(f"Second running Thread: {t2}")
time.sleep(4) # Need to sleep to give Threads time to complete
cleanup_interpreters()
上面的代碼中演示瞭如何使用 _xxsubinterpreters
模塊來實現 (方法一)
我們還在每個線程中休眠 2 秒來模擬“工作”狀態
請註意,我們甚至不必調用 join() 函數等待線程完成,只需線上程完成時清理解釋器即可
Channels
如果我們進一步挖掘 CPython test
模塊,我們還會發現 RecvChannel 和 SendChannel 類的實現類似於 Golang 中已知的通道
# https://github.com/python/cpython/blob/
# 15665d896bae9c3d8b60bd7210ac1b7dc533b093/Lib/test/test_interpreters.py#L583
r, s = interpreters.create_channel()
print(f"Channel: {r}, {s}")
# Channel: RecvChannel(id=0), SendChannel(id=0)
orig = b'spam'
s.send_nowait(orig)
obj = r.recv()
print(f"Received: {obj}")
# Received: b'spam'
cleanup_interpreters()
# Need clean up, otherwise:
# free(): invalid pointer
# Aborted (core dumped)
上面的例子介紹瞭如何創建一個接收端通道(r)和發送端通道(s),然後我們使用 send_nowait
方法將數據發送,通過 recv
方法來接收數據
這個通道實際上只是另一個解釋器,和以前一樣,我們需要在處理完它之後進行清理
Digging Deeper
如果我們想要修改或者調整子解釋器的選項(這些選項通常在 C 代碼中設置),我們可以使用
test.support
模塊中的代碼,具體來說是run_in_subinterp_with_config
import test.support
def run_in_thread(script):
test.support.run_in_subinterp_with_config(
script,
use_main_obmalloc=True,
allow_fork=True,
allow_exec=True,
allow_threads=True,
allow_daemon_threads=False,
check_multi_interp_extensions=False,
own_gil=True,
)
code = dedent(f"""
from test.support import interpreters
cur = interpreters.get_current()
print(cur)
""")
run_in_thread(code)
# Interpreter(id=7, isolated=None)
run_in_thread(code)
# Interpreter(id=8, isolated=None)
上面這個run_in_subinterp_with_config
函數是 C 函數的 Python API。它提供了一些子解釋器選項,如 own_gil
,指定子解釋器是否應該擁有自己的 GIL