目录

1. 简介2. Python历史3. 安装Python3.1. Python解释器4. 第一个Python程序4.1. 使用文本编辑器4.2. 输入和输出5. Python基础5.1. 数据类型和变量5.2. 字符串和编码5.3. 使用list和tuple5.4. 条件判断5.5. 模式匹配5.6. 循环5.7. 使用dict和set6. 函数6.1. 调用函数6.2. 定义函数6.3. 函数的参数6.4. 递归函数7. 高级特性7.1. 切片7.2. 迭代7.3. 列表生成式7.4. 生成器7.5. 迭代器8. 函数式编程8.1. 高阶函数8.1.1. map/reduce8.1.2. filter8.1.3. sorted8.2. 返回函数8.3. 匿名函数8.4. 装饰器8.5. 偏函数9. 模块9.1. 使用模块9.2. 安装第三方模块10. 面向对象编程10.1. 类和实例10.2. 访问限制10.3. 继承和多态10.4. 获取对象信息10.5. 实例属性和类属性11. 面向对象高级编程11.1. 使用__slots__11.2. 使用@property11.3. 多重继承11.4. 定制类11.5. 使用枚举类11.6. 使用元类12. 错误、调试和测试12.1. 错误处理12.2. 调试12.3. 单元测试12.4. 文档测试13. IO编程13.1. 文件读写13.2. StringIO和BytesIO13.3. 操作文件和目录13.4. 序列化14. 进程和线程14.1. 多进程14.2. 多线程14.3. ThreadLocal14.4. 进程 vs. 线程14.5. 分布式进程15. 正则表达式16. 常用内建模块16.1. datetime16.2. collections16.3. argparse16.4. base6416.5. struct16.6. hashlib16.7. hmac16.8. itertools16.9. contextlib16.10. urllib16.11. XML16.12. HTMLParser16.13. venv17. 常用第三方模块17.1. Pillow17.2. requests17.3. chardet17.4. psutil18. 图形界面18.1. 海龟绘图19. 网络编程19.1. TCP/IP简介19.2. TCP编程19.3. UDP编程20. 电子邮件20.1. SMTP发送邮件20.2. POP3收取邮件21. 访问数据库21.1. 使用SQLite21.2. 使用MySQL21.3. 使用SQLAlchemy22. Web开发22.1. HTTP协议简介22.2. HTML简介22.3. WSGI接口22.4. 使用Web框架22.5. 使用模板23. 异步IO23.1. 协程23.2. 使用asyncio23.3. 使用aiohttp24. FAQ25. 期末总结

14.3. ThreadLocal

但是局部变量也有问题,就是在函数调用的时候,传递起来很麻烦:

def process_student(name):
    std = Student(name)
    # std是局部变量,但是每个函数都要用它,因此必须传进去:
    do_task_1(std)
    do_task_2(std)

def do_task_1(std):
    do_subtask_1(std)
    do_subtask_2(std)

def do_task_2(std):
    do_subtask_2(std)
    do_subtask_2(std)

每个函数一层一层调用都这么传参数那还得了?用全局变量?也不行,因为每个线程处理不同的Student对象,不能共享。

如果用一个全局dict存放所有的Student对象,然后以thread自身作为key获得线程对应的Student对象如何?

global_dict = {}

def std_thread(name):
    std = Student(name)
    # 把std放到全局变量global_dict中:
    global_dict[threading.current_thread()] = std
    do_task_1()
    do_task_2()

def do_task_1():
    # 不传入std,而是根据当前线程查找:
    std = global_dict[threading.current_thread()]
    ...

def do_task_2():
    # 任何函数都可以查找出当前线程的std变量:
    std = global_dict[threading.current_thread()]
    ...

这种方式理论上是可行的,它最大的优点是消除了std对象在每层函数中的传递问题,但是,每个函数获取std的代码有点丑。

有没有更简单的方式?

ThreadLocal应运而生,不用查找dictThreadLocal帮你自动做这件事:

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=('Alice',), name='Thread-A')
t2 = threading.Thread(target= process_thread, args=('Bob',), name='Thread-B')
t1.start()
t2.start()
t1.join()
t2.join()

执行结果:

Hello, Alice (in Thread-A)
Hello, Bob (in Thread-B)

全局变量local_school就是一个ThreadLocal对象,每个Thread对它都可以读写student属性,但互不影响。你可以把local_school看成全局变量,但每个属性如local_school.student都是线程的局部变量,可以任意读写而互不干扰,也不用管理锁的问题,ThreadLocal内部会处理。

可以理解为全局变量local_school是一个dict,不但可以用local_school.student,还可以绑定其他变量,如local_school.teacher等等。

ThreadLocal最常用的地方就是为每个线程绑定一个数据库连接,HTTP请求,用户身份信息等,这样一个线程的所有调用到的处理函数都可以非常方便地访问这些资源。

小结

一个ThreadLocal变量虽然是全局变量,但每个线程都只能读写自己线程的独立副本,互不干扰。ThreadLocal解决了参数在一个线程中各个函数之间互相传递的问题。

参考源码

use_threadlocal.py