Python中的多線程可以通過共享全局變量或者使用共享內存來共享變量。以下是幾種常見的方法:
import threading
global_var = 0
lock = threading.Lock()
def increment_global_var():
global global_var
with lock:
global_var += 1
threads = []
for _ in range(10):
t = threading.Thread(target=increment_global_var)
threads.append(t)
t.start()
for t in threads:
t.join()
print(global_var)
multiprocessing
模塊中的Value
或者Array
來創建共享內存對象,多個線程可以同時訪問和修改這些共享內存對象。import threading
from multiprocessing import Value
shared_var = Value('i', 0)
def increment_shared_var():
with shared_var.get_lock():
shared_var.value += 1
threads = []
for _ in range(10):
t = threading.Thread(target=increment_shared_var)
threads.append(t)
t.start()
for t in threads:
t.join()
print(shared_var.value)
無論使用哪種方法,都需要注意保護共享變量,避免多個線程同時修改導致數據不一致的問題。