哈嘍大家好,我是咸魚
幾天前,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
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/553406.html
標籤:其他
下一篇:返回列表
