Python多线程-ThreadLocal

参考:https://www.liaoxuefeng.com/wiki/1016959663602400/1017630786314240#0

ThreadLocal

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

import threading

# 创建全局ThreadLocal对象
locals_school = threading.local()


def process_student():
    # 获取当前线程关联的student: student是线程的局部变量,可以任意读写而互不干扰,
    # 也不用管理锁的问题,ThreadLocal内部会处理。
    std = locals_school.student
    print(f'Hello, {std} ,线程名称 {threading.current_thread().name}')


def process_thread(name: str):
    # 绑定ThreadLocal的student属性
    locals_school.student = name
    process_student()


t1 = threading.Thread(target=process_thread, args=('李好',))
t2 = threading.Thread(target=process_thread, args=('王大毛',))

t1.start()
t2.start()
t1.join()
t2.join()

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

posted @ 2020-07-20 14:23  zy7y  阅读(298)  评论(0编辑  收藏  举报