在Python中,多線程共享全局變量可以使用以下幾種方式實現:
import threading
def thread_func():
global shared_variable
# 使用 shared_variable
# 創建多個線程
threads = []
for _ in range(10):
t = threading.Thread(target=thread_func)
threads.append(t)
t.start()
# 等待所有線程結束
for t in threads:
t.join()
import threading
shared_variable = 0
lock = threading.Lock()
def thread_func():
global shared_variable
lock.acquire()
try:
# 修改 shared_variable
finally:
lock.release()
# 創建多個線程
threads = []
for _ in range(10):
t = threading.Thread(target=thread_func)
threads.append(t)
t.start()
# 等待所有線程結束
for t in threads:
t.join()
import threading
thread_local = threading.local()
def thread_func():
# 使用 thread_local.variable
# 設置每個線程的變量副本
for _ in range(10):
thread_local.variable = 0
t = threading.Thread(target=thread_func)
t.start()
# 等待所有線程結束
for t in threads:
t.join()
需要根據具體的需求選擇適合的方法來實現多線程共享全局變量。