python thread.local()的实例化

2025-12-01 0 66,739

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()的实例化,希望对大家有所帮助。更多Python学习指路:python基础教程

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:以上部本文内容由互联网用户自发贡献,本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。投诉邮箱:3758217903@qq.com

ZhiUp资源网 python基础 python thread.local()的实例化 https://www.zhiup.top/1875.html

相关