在多线程环境下,每个线程都有⾃⼰的数据。
⼀个线程使⽤⾃⼰的局部变量 ⽐使⽤全局变量好,因为局部变量只有线程⾃⼰能看⻅,不会影响其他线 程,⽽全局变量的修改必须加锁
⼀个ThreadLocal变量虽然是全局变量,但每个线程都只能读写⾃⼰线程的独 ⽴副本,互不⼲扰。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=('dongGe',), name='Thread-A')
t2 = threading.Thread(target= process_thread, args=('老王',), name='Thread-B')
t1.start()
t2.start()
全局变量local_school就是⼀个ThreadLocal对象,每个Thread对它都可以读 写student属性,但互不影响。你可以把local_school看成全局变量,但每个 属性如local_school.student都是线程的局部变量,可以任意读写⽽互不⼲ 扰,也不⽤管理锁的问题,ThreadLocal内部会处理
ThreadLocal最常⽤的地⽅就是为每个线程绑定⼀个数据库连接,HTTP请 求,⽤户身份信息等,这样⼀个线程的所有调⽤到的处理函数都可以⾮常⽅ 便地访问这些资源