怎么在python中使用thread.local()实现实例化?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
Python主要应用于:1、Web开发;2、数据科学研究;3、网络爬虫;4、嵌入式应用开发;5、游戏开发;6、桌面应用开发。
1、说明
threading.local()实例化全局对象,该全局对象有大字典,键值为两个弱引用对象{线程对象、字典对象},通过current_thread()获取当前线程对象,并根据该对象获取相应的字典对象。
2、实例
import threading
import random
data = threading.local()
def show(d):
try:
num = d.num
except AttributeError:
print("线程 %s 还未设置该属性!" % threading.current_thread().getName())
else:
print("线程 %s 中该属性的值为 = %s" % (threading.current_thread().getName(), num))
def thread_call(d):
show(d)
d.num = random.randint(1, 100)
show(d)
if __name__ == '__main__':
show(data)
data.num = 666
show(data)
for i in range(2):
t = threading.Thread(target=thread_call, args=(data,), name="Thread " + str(i)) t.start()
看完上述内容,你们掌握怎么在python中使用thread.local()实现实例化的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://www.py.cn/jishu/jichu/28142.html