Threadlocal

本文首发于知乎
考虑下面一种情形

  • 有一些人的信息person_list = [{'name': 'Bob', 'score': 5}, {'name': 'Mary', 'score': 4}]
  • 用两个线程分别更新两个人的score,第一次加1,第二次平方,再设定一个count变量表示更新的次数

我们可以看出上面提到的scorecount都有全局变量的感觉,但是又不完全是,因为他们只能属于一个person而不是整个全局。这种情况本方法可以有两个

  • 一种方法是函数之间构造中间变量进行传递,但是这样代码非常冗余
  • 一种方法是创造全局变量,但是有多个person,如果要全局变量只能创造一个字典,每个人再分别提取

我们来看一下第二种方法

from threading import Thread
global_dict = {'bob': {'name': 'Bob', 'score': 5, 'count': 0},
'mary': {'name': 'Mary', 'score': 4, 'count': 0}}
def work(person):
print('start score', global_dict[person]['score'])
update_first(person)
update_second(person)
print('end count', global_dict[person]['count'])
def update_first(person):
global global_dict
global_dict[person]['score'] = global_dict[person]['score'] + 1
print(global_dict[person]['name'], 'first new score is', global_dict[person]['score'])
global_dict[person]['count'] += 1
def update_second(person):
global global_dict
global_dict[person]['score'] = global_dict[person]['score'] * global_dict[person]['score']
print(global_dict[person]['name'], 'second new score is', global_dict[person]['score'])
global_dict[person]['count'] += 1
Thread(target = work, args = ('bob', )).start()
Thread(target = work, args = ('mary', )).start()
复制代码

运行结果如下

start score 5
Bob first new score is 6
Bob second new score is 36
start score 4
end count 2
Mary first new score is 5
Mary second new score is 25
end count 2
复制代码

一直调用全局变量字典使代码非常冗余,有两种比较好的方法

  • 类的形式
  • ThreadLocal

首先来看一下写成类的形式

from threading import Thread
class MyThread(Thread):
def __init__(self, name, score):
Thread.__init__(self)
self.name = name
self.score = score
self.count = 0
def run(self):
print('start score', self.score)
self.update_first()
self.update_second()
print('end count', self.count)
def update_first(self):
self.score = self.score + 1
print(self.name, 'first new score is', self.score)
self.count += 1
def update_second(self):
self.score = self.score * self.score
print(self.name, 'second new score is', self.score)
self.count += 1
MyThread('Bob', 5).start()
MyThread('Mary', 4).start()
复制代码

输出结果如下

start score 5
Bob first new score is 6
Bob second new score is 36
start score 4
end count 2
Mary first new score is 5
Mary second new score is 25
end count 2
复制代码

我们知道,threading模块中多线程实现有两种方式,上面从类继承是一种,还有一种是将函数传入Thread中。第二种就需要使用threadlocal才能比较好地实现上述过程。代码如下

import threading
local = threading.local()
def work(name, score):
local.name = name
local.score = score
local.count = 0
print('start score', local.score)
update_first()
update_second()
print('end count', local.count)
def update_first():
local.score = local.score + 1
print(local.name, 'first new score is', local.score)
local.count += 1
def update_second():
local.score = local.score * local.score
print(local.name, 'second new score is', local.score)
local.count += 1
threading.Thread(target = work, args = ('Bob', 5)).start()
threading.Thread(target = work, args = ('Mary', 4)).start()
复制代码

运行结果如下

start score 5
Bob first new score is 6
Bob second new score is 36
start score 4
end count 2
Mary first new score is 5
Mary second new score is 25
end count 2
复制代码

所以说threadlocal就是用于处理那种介于全局变量和局部变量之间的变量的。

欢迎关注我的知乎专栏

专栏主页:python编程

专栏目录:目录

版本说明:软件及包版本说明

### ThreadLocal的使用场景 ThreadLocal适用于需要在多线程环境中为每个线程独立存储和操作数据的场景。常见的使用场景包括: - **线程上下文传递**:例如在Web应用中,每个请求由一个线程处理,可以通过ThreadLocal保存请求相关的上下文信息,如用户身份、事务对象等,避免频繁传递参数[^2]。 - **线程安全的变量管理**:当多个线程需要访问某个变量,但每个线程对该变量的操作互不影响时,可以使用ThreadLocal来避免同步开销[^3]。 - **资源持有**:某些资源(如数据库连接、Session等)需要在线程内部共享,但不希望多个线程之间共享,ThreadLocal可以很好地满足这种需求[^1]。 ### ThreadLocal的实现原理 ThreadLocal的实现机制主要依赖于线程内部的ThreadLocalMap结构: - 每个线程(Thread类)内部维护一个ThreadLocalMap对象,该Map的键为ThreadLocal实例,值为存储的变量副本[^4]。 - ThreadLocalMap使用**弱引用(WeakReference)**作为键,以避免内存泄漏。当ThreadLocal对象不再被外部引用时,垃圾回收器可以正常回收该对象,但需要注意Map中对应的值仍需手动清理[^5]。 - 每个ThreadLocal实例都有一个唯一的哈希码(threadLocalHashCode),用于在ThreadLocalMap中快速定位存储位置[^5]。 通过这种机制,每个线程访问同一个ThreadLocal变量时,实际上访问的是各自线程独立的变量副本,从而实现了线程安全。 ### 示例代码 以下是一个简单的ThreadLocal使用示例: ```java public class ThreadLocalExample { // 定义一个ThreadLocal变量 private static ThreadLocal<Integer> threadLocal = new ThreadLocal<>(); public static void main(String[] args) { // 创建多个线程进行测试 for (int i = 0; i < 3; i++) { new Thread(() -> { // 设置线程本地变量 threadLocal.set((int) (Math.random() * 100)); // 获取线程本地变量 System.out.println(Thread.currentThread().getName() + ": " + threadLocal.get()); }).start(); } } } ``` 在这个例子中,每个线程都设置了不同的整数值,彼此之间互不影响。 ### 总结 ThreadLocal通过为每个线程提供独立的变量副本,解决了线程安全问题,并在某些场景下提升了性能。其核心在于每个线程内部维护的ThreadLocalMap结构,以及基于弱引用的键值对管理机制。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值