我是一名 java 工程師,我正在嘗試找到一種方法來使類中的方法呼叫執行緒安全,如下所示的代碼片段:
class A:
def __init__(self, id):
self.x = X(id)
def switch(self, new_id):
self.x = X(new_id) # switch to another object
def log(self, msg):
self.x.log(msg)
a = A()
我想知道,如果a被多執行緒使用,并且有時switch會呼叫方法,那么方法是否會log受到NullPointerExceptionself.x 可能為 None 的影響?
謝謝!
uj5u.com熱心網友回復:
程式中的任何時候都不會self.x設定為None. 如果我們查看為switch函式生成的 Python 位元組碼,我們會看到它self.x立即被新X實體替換,而沒有設定為None:
# Create the new X instance
0 LOAD_GLOBAL 0 (X)
2 LOAD_FAST 1 (new_id)
4 CALL_FUNCTION 1
# Store the new self.x
6 LOAD_FAST 0 (self)
8 STORE_ATTR 1 (x)
# Return from the function
10 LOAD_CONST 0 (None)
12 RETURN_VALUE
仔細檢查不會有任何NullPointerException類似這樣的錯誤:
AttributeError: 'NoneType' object has no attribute 'log'
我創建了一個簡單的 Python 腳本,它在兩個單獨的執行緒中重復呼叫switch和log方法,而不會獲取任何鎖。
import threading
import random
class X:
def __init__(self, id) -> None:
self.id = id
def log(self, msg):
print(f'{self.id}: {msg}')
class A:
def __init__(self, id):
self.x = X(id)
def switch(self, new_id):
self.x = X(new_id) # switch to another object
def log(self, msg):
self.x.log(msg)
a = A(0)
def switch_t():
while True:
a.switch(random.randint(0, 100))
def log_t():
while True:
a.log(random.randint(0, 100))
t1 = threading.Thread(target=switch_t)
t2 = threading.Thread(target=log_t)
t1.start()
t2.start()
我運行了這段代碼兩分鐘,它從來沒有拋出任何錯誤。
所以,只要你self.x在執行程序中不需要保持不變log,萬一你想訪問self.x不止一次,你的代碼是完全沒問題的,你不會遇到任何NullPointerException類似的錯誤。
還有一件事要指出,在 中a = A(),您忘記了建構式引數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/504227.html
標籤:Python python-3.x 多线程
上一篇:boostbeast同步應用程式-是否需要顯式并發處理?
下一篇:vtable何時創建/填充?
