對于一些簡單的執行緒相關代碼,即:
import threading
a = 0
threads = []
def x():
global a
for i in range(1_000_000):
a = 1
for _ in range(10):
thread = threading.Thread(target=x)
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
print(a)
assert a == 10_000_000
我們得到了不同的行為,基于 Python 版本。
對于 3.10,輸出為:
? python3.10 b.py
10000000
對于 3.9,輸出為:
? python3.9 b.py
2440951
Traceback (most recent call last):
File "/Users/romka/t/threads-test/b.py", line 24, in <module>
assert a == 10_000_000
AssertionError
由于我們沒有獲取任何鎖,對我來說,3.9 的結果是顯而易見的和預期的。問題是為什么以及如何 3.10 得到“正確”的結果,而不應?
我正在審查 Python 3.10 的變更日志,沒有任何與執行緒或 GIL 相關的內容可以帶來這樣的結果。
uj5u.com熱心網友回復:
核心開發人員的回答:
重構快速操作碼調度的 Mark Shannon 更改的意外后果:https : //github.com/python/cpython/commit/4958f5d69dd2bf86866c43491caf72f774ddec97 - INPLACE_ADD 操作碼不再使用“慢”這樣的調度路徑來檢查中斷和。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/359316.html
標籤:Python 多线程 python-多线程
