它來了!真正的 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
  • Dapr Outbox 是1.12中的功能。 本文只介紹Dapr Outbox 執行流程,Dapr Outbox基本用法請閱讀官方文檔 。本文中appID=order-processor,topic=orders 本文前提知識:熟悉Dapr狀態管理、Dapr發佈訂閱和Outbox 模式。 Outbo ...
  • 引言 在前幾章我們深度講解了單元測試和集成測試的基礎知識,這一章我們來講解一下代碼覆蓋率,代碼覆蓋率是單元測試運行的度量值,覆蓋率通常以百分比表示,用於衡量代碼被測試覆蓋的程度,幫助開發人員評估測試用例的質量和代碼的健壯性。常見的覆蓋率包括語句覆蓋率(Line Coverage)、分支覆蓋率(Bra ...
  • 前言 本文介紹瞭如何使用S7.NET庫實現對西門子PLC DB塊數據的讀寫,記錄了使用電腦模擬,模擬PLC,自至完成測試的詳細流程,並重點介紹了在這個過程中的易錯點,供參考。 用到的軟體: 1.Windows環境下鏈路層網路訪問的行業標準工具(WinPcap_4_1_3.exe)下載鏈接:http ...
  • 從依賴倒置原則(Dependency Inversion Principle, DIP)到控制反轉(Inversion of Control, IoC)再到依賴註入(Dependency Injection, DI)的演進過程,我們可以理解為一種逐步抽象和解耦的設計思想。這種思想在C#等面向對象的編 ...
  • 關於Python中的私有屬性和私有方法 Python對於類的成員沒有嚴格的訪問控制限制,這與其他面相對對象語言有區別。關於私有屬性和私有方法,有如下要點: 1、通常我們約定,兩個下劃線開頭的屬性是私有的(private)。其他為公共的(public); 2、類內部可以訪問私有屬性(方法); 3、類外 ...
  • C++ 訪問說明符 訪問說明符是 C++ 中控制類成員(屬性和方法)可訪問性的關鍵字。它們用於封裝類數據並保護其免受意外修改或濫用。 三種訪問說明符: public:允許從類外部的任何地方訪問成員。 private:僅允許在類內部訪問成員。 protected:允許在類內部及其派生類中訪問成員。 示 ...
  • 寫這個隨筆說一下C++的static_cast和dynamic_cast用在子類與父類的指針轉換時的一些事宜。首先,【static_cast,dynamic_cast】【父類指針,子類指針】,兩兩一組,共有4種組合:用 static_cast 父類轉子類、用 static_cast 子類轉父類、使用 ...
  • /******************************************************************************************************** * * * 設計雙向鏈表的介面 * * * * Copyright (c) 2023-2 ...
  • 相信接觸過spring做開發的小伙伴們一定使用過@ComponentScan註解 @ComponentScan("com.wangm.lifecycle") public class AppConfig { } @ComponentScan指定basePackage,將包下的類按照一定規則註冊成Be ...
  • 操作系統 :CentOS 7.6_x64 opensips版本: 2.4.9 python版本:2.7.5 python作為腳本語言,使用起來很方便,查了下opensips的文檔,支持使用python腳本寫邏輯代碼。今天整理下CentOS7環境下opensips2.4.9的python模塊筆記及使用 ...