在多線程環(huán)境下,如果多個(gè)線程同時(shí)訪問和修改共享數(shù)據(jù)(例如,字典、列表等),可能會(huì)導(dǎo)致數(shù)據(jù)不一致或其他未定義的行為
以下是一個(gè)使用threading.Lock
保護(hù)字典更新操作的示例:
import threading
class SafeDict(dict):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._lock = threading.Lock()
def update(self, *args, **kwargs):
with self._lock:
super().update(*args, **kwargs)
# 示例用法
safe_dict = SafeDict()
def update_dict(key, value):
safe_dict.update({key: value})
# 創(chuàng)建并啟動(dòng)多個(gè)線程,同時(shí)更新字典
threads = []
for i in range(10):
t = threading.Thread(target=update_dict, args=(i, i * 2))
threads.append(t)
t.start()
# 等待所有線程完成
for t in threads:
t.join()
print(safe_dict)
這個(gè)示例中,我們創(chuàng)建了一個(gè)名為SafeDict
的自定義字典類,它繼承自內(nèi)置的dict
類。我們?cè)?code>SafeDict中添加了一個(gè)鎖(threading.Lock
),并在update
方法中使用with
語句確保在更新字典時(shí)持有鎖。這樣,在多線程環(huán)境下,只有一個(gè)線程能夠同時(shí)更新字典,從而避免了數(shù)據(jù)不一致的問題。
請(qǐng)注意,這種方法可能會(huì)降低程序的性能,因?yàn)榫€程需要等待獲取鎖。在高并發(fā)場(chǎng)景下,可以考慮使用其他并發(fā)原語,如Semaphore
、Condition
或Event
,或者使用線程安全的數(shù)據(jù)結(jié)構(gòu),如queue.Queue
。