您好,欢迎来到二三四教育网。
搜索
您的当前位置:首页python thread.local()的实例化

python thread.local()的实例化

来源:二三四教育网

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学习指路:

本文如未解决您的问题请添加抖音号:51dongshi(抖音搜索懂视),直接咨询即可。

热门图文

Copyright © 2019-2025 how234.cn 版权所有 赣ICP备2023008801号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务