上一节介绍了多线程间的共享问题。本节介绍,使用threading模块的ThreadLocal来创建一个全局变量,每个线程可以为这个变量绑定只属于自己的局部属性。
import threading
# 创建全局ThreadLocal对象:
local_school = threading.local()
def process_student():
# 获取当前线程关联的student:
std = local_school.student
print('Hello, %s (in %s)' % (std, threading.current_thread().name))
def process_thread(name):
# 绑定ThreadLocal的student:
local_school.student = name
process_student()
t1 = threading.Thread(target= process_thread, args=(