它來了!真正的 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
  • 在一些複雜的業務表中間查詢數據,有時候操作會比較複雜一些,不過基於SqlSugar的相關操作,處理的代碼會比較簡單一些,以前我在隨筆《基於SqlSugar的開發框架循序漸進介紹(2)-- 基於中間表的查詢處理》介紹過基於主表和中間表的聯合查詢,而往往實際會比這個會複雜一些。本篇隨筆介紹聯合多個表進行... ...
  • 從按鈕、文本框到下拉框、列表框,WPF提供了一系列常用控制項,每個控制項都有自己獨特的特性和用途。通過靈活的佈局容器,如網格、堆棧面板和換行面板,我們可以將這些控制項組合在一起,實現複雜的界面佈局。而通過樣式和模板,我們可以輕鬆地定製控制項的外觀和行為,以符合我們的設計需求。本篇記錄WPF入門需要瞭解的樣式... ...
  • 以MySQL資料庫為例 # 一. 安裝 NuGet搜索Dapper.Lite並安裝最新版本。 ![](https://img2023.cnblogs.com/blog/174862/202306/174862-20230602155913303-757935399.jpg) NuGet搜索MySql ...
  • # 圖片介面JWT鑒權實現 # 前言 之前做了個返回圖片鏈接的介面,然後沒做授權,然後今天鍵盤到了,也是用JWT來做介面的許可權控制。 然後JTW網上已經有很多文章來說怎麼用了,這裡就不做多的解釋了,如果不懂的可以參考下列鏈接的 文章。 圖片介面文章:[還在愁個人博客沒有圖片放?](https://w ...
  • ![線程各屬性縱覽](https://img2023.cnblogs.com/blog/1220983/202306/1220983-20230603114109107-477345835.png) 如上圖所示,線程有四個屬性: - 線程ID - 線程名稱 - 守護線程 - 線程優先順序 ### 1. ...
  • 本次主要介紹golang中的標準庫`bytes`,基本上參考了 [位元組 | bytes](https://cloud.tencent.com/developer/section/1140520) 、[Golang標準庫——bytes](https://www.jianshu.com/p/e6f7f2 ...
  • 歡迎來到本篇文章!通過上一篇什麼是 Spring?為什麼學它?的學習,我們知道了 Spring 的基本概念,知道什麼是 Spring,以及為什麼學習 Spring。今天,這篇就來說說 Spring 中的核心概念之一 IoC。 ...
  • # 2022版本IDEA+Maven+Tomcat的第一個程式(傻瓜教學) ​ 作為學習Javaweb的一個重要環節,如何實現在IDEA中利用Maven工具創建一個Javaweb程式模版並連接Tomcat發佈是非常重要的。我比較愚鈍(小白),而且自身電腦先前運行過spring或maven的程式,系統 ...
  • 本篇專門扯一下有關 QCheckBox 組件的一個問題。老周不水字數,直接上程式,你看了就明白。 #include <QApplication> #include <QWidget> #include <QPushButton> #include <QCheckBox> #include <QVBo ...
  • # 1.列表數據元素排序 在創建的列表中,數據元素的排列順序常常是無法預測的。這雖然在大多數情況下都是不可避免的,但經常需要以特定的順序呈現信息。有時候希望保留列表數據元素最初的排列順序,而有時候又需要調整排列順序。python提供了很多列表數據元素排序的方式,可根據情況選用。 ## 1.永久性排序 ...