在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()
需要根据具体的需求选择适合的方法来实现多线程共享全局变量。