Python的线程22 Threading.local() 线程的本地数据

「这是我参与2022首次更文挑战的第11天,活动详情查看:2022首次更文挑战」。

正式的Python专栏第59篇,同学站住,别错过这个从0开始的文章!

就快过年了,有在看文章的读者,可以继续给学委点赞,关注也不错!

前面介绍了多线程(threading)库里面的很多类,好像把local这个整漏了,下面直接来。

什么是线程的本地数据?

线程的本地数据,就是专属于特定一个线程的数据。

再看看怎么创建线程本地数据,创建方式为threading.local(),学委准备了如下代码:

tldata = threading.local()
tldata.slogan = "持续学习,持续开发,我是雷学委!"


# Call by below code will get no attribute exception
# AttributeError: '_MainThread' object has no attribute 'slogan'
print("current thread slogan:%s ",threading.current_thread().slogan)
复制代码

我们这里直接运行,获取当前线程,发现不能直接线程对象 + “.slogan" 的方式获取属性。

这里说明threading.local()的后续修改不会修改线程的属性。

好,下面代码,就展示到了两个线程获取各自的本地数据。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2022/1/30 11:36 下午
# @Author : LeiXueWei
# @CSDN/Juejin/Wechat: 雷学委
# @XueWeiTag: CodingDemo
# @File : threading_local.py
# @Project : hello
import threading

tldata = threading.local()
tldata.slogan = "持续学习"


# Call by below code will get no attribute exception
# AttributeError: '_MainThread' object has no attribute 'slogan'
# print("current thread slogan:%s ",threading.current_thread().slogan)


def print_thread_data():
    print("学委demo-thread %s : tldata=%s " % (threading.current_thread().name, tldata))
    current_tl_data = threading.local()
    print("学委demo-thread %s : current_tl_data=%s " % (threading.current_thread().name, current_tl_data))



print("thread %s : tldata:%s " % (threading.current_thread().name, tldata))
t1 = threading.Thread(name="another thread", target=print_thread_data)
t1.start()

print("thread %s : tldata:%s " % (threading.current_thread().name, tldata))
复制代码

运行效果如下:

屏幕快照 2022-01-30 下午11.54.17.png

从运行结果,我们可以发现,tldata这个属于主线程的本地数据,是可以被传递到前提线程的target调用函数内的。

这没啥问题。

重点是,我们在t1线程内执行threading.local()获取到的current_tl_data,并不跟tldata相同(它们并不指向同个内存地址。

至此,已经展示了threading.local()创建本地数据的特点了。

每个线程内调用这个方法,获取的是本线程专属的本地数据。

当然,如果我们把主线程的本地数据的变量,传递到其他线程,被它们修改了,那么肯定是会被修改的。这个没毛病。

所以,使用本地数据,我们更多是希望这份专属的数据只被持有的线程操纵。

总结

线程本地数据不是一个共享多个线程的数据,这样我们在使用它的时候,不用过多的担心拿到脏数据。

也就是说,不必担心线程的本地数据被其他线程攥改,导致出现超出本线程预期的逻辑漏洞。

喜欢Python的朋友,请关注学委的 Python基础专栏 or Python入门到精通大专栏

喜欢Python的朋友,请关注学委的 Python基础专栏 or Python入门到精通大专栏

持续学习持续开发,我是雷学委!
编程很有趣,关键是把技术搞透彻讲明白。
欢迎关注微信,点赞支持收藏!

Guess you like

Origin juejin.im/post/7059029083358756894