python - threadlocal

功能:给线程创建一些变量,线程彼此之间是完全隔离的,每个线程使用各自的变量。

常用场景:

数据库会话

业务开始时,获取连接,业务结束时,关闭连接,中间的业务是未知的。这种场景下,想要管理数据库连接,通常要用 threadlocal。

处理上下文

做后台接口的时候,需要获取登录的用户信息,任何业务都可能产生这一需求,但是,不可能通过参数传递用户信息。这时候,就可以把登录的用户信息放到 threadlocal。


import threading
 
# 创建 threading.local 的实例
local = threading.local()
 
def process_thread(i):
    # 每个线程可以访问和修改自己的 local 变量
    local.number = i
    print(f'Thread {threading.current_thread().name} sets local.number to: {local.number}')
 
    # 修改 local 变量
    local.number += 1
    print(f'Thread {threading.current_thread().name} changes local.number to: {local.number}')
 
    # 其他线程无法访问到这个修改
 
# 创建并启动线程
threads = [threading.Thread(target=process_thread, args=(i,)) for i in range(4)]
for t in threads:
    t.start()
for t in threads:
    t.join()

posted on 2024-12-02 10:37  疯狂的妞妞  阅读(161)  评论(0)    收藏  举报

导航