它來了!真正的 python 多線程

来源:https://www.cnblogs.com/edisonfish/archive/2023/05/25/17431316.html
-Advertisement-
Play Games

哈嘍大家好,我是鹹魚 幾天前,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 代碼庫中有一些代碼段向我們展示瞭如何使用它:

  1. 方法一:我們可以使用 _xxsubinterpreters 模塊(因為是通過 C 實現的,所以命名比較奇怪,而且在 python 中不能夠簡單地去檢查代碼)
  2. 方法二:可以使用 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


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • [toc] 你好!我是[@馬哥python說](https://www.zhihu.com/people/13273183132),一名10年程式猿,正在試錯用pyecharts開發可視化大屏的非常規排版。 以下,我用8種ThemeType展示的同一個可視化數據大屏,可視化主題是分析**“淄博燒烤” ...
  • 來源:https://www.duidaima.com/Group/Topic/JAVA/11942 ## **1、什麼是狀態機** ### 1.1 什麼是狀態 先來解釋什麼是“狀態”( State )。現實事物是有不同狀態的,例如一個自動門,就有 open 和 closed 兩種狀態。我們通常所說 ...
  • [toc] # 高階函數 高階函數是將函數用作參數或返回值的函數,還可以把函數賦值給一個變數。 所有函數類型都有一個圓括弧括起來的參數類型列表以及一個返回類型:(A, B) -> C 表示接受類型分別為 A 與 B 兩個參數並返回一個 C 類型值的函數類型。 參數類型列表可以為空,如 () -> A ...
  • 本文將為大家詳細講解Java中的Map集合,這是我們進行開發時經常用到的知識點,也是大家在學習Java中很重要的一個知識點,更是我們在面試時有可能會問到的問題。文章較長,乾貨滿滿,建議大家收藏慢慢學習。文末有本文重點總結,主頁有全系列文章分享。技術類問題,歡迎大家和我們一起交流討論! ...
  • # 0.相關確定 本教程使用的版本號為專業版PyCharm 2022.3.2,如果您是初學者,為了更好的學習本教程,避免不必要的麻煩,請您下載使用與本教程一致的版本號。 # 1.PyCharm的下載 官網下載:https://www.jetbrains.com/pycharm/download/ot ...
  • Servlet是web體系裡面最重要的部分,下麵羅列幾道常見的面試題,小伙伴們一定要好好記住哈。 1.Servlet是單例的嗎,如何證明? Servlet一般都是單例的,並且是多線程的。如何證明Servlet是單例模式呢?很簡單,重寫Servlet的init方法,或者添加一個構造方法。然後,在web ...
  • Rocksdb作為當下nosql中性能的代表被各個存儲組件(mysql、tikv、pmdk、bluestore)作為存儲引擎底座,其基於LSM tree的核心存儲結構(將隨機寫通過數據結構轉化為順序寫)來提供高性能的寫吞吐時保證了讀性能。同時大量的併發性配置來降低compaction的影響。 ...
  • 本篇為[用go設計開發一個自己的輕量級登錄庫/框架吧]的封禁業務篇,會講講封禁業務的實現,給庫/框架增加新的功能。源碼:https://github.com/weloe/token-go ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...