zoukankan      html  css  js  c++  java
  • 多线程threading.local的作用及原理?

    1.示例代码

    import time
    import threading
    
    v = threading.local()
    
    def func(arg):
        # 内部会为当前线程创建一个空间用于存储:phone=自己的值
        v.phone = arg
        time.sleep(2)
        print(v.phone,arg) # 去当前线程自己空间取值
    
    for i in range(10):
        t =threading.Thread(target=func,args=(i,))
        t.start()
    

    2.原理

    import time
    import threading
    
    DATA_DICT = {}
    
    def func(arg):
        ident = threading.get_ident()
        DATA_DICT[ident] = arg
        time.sleep(1)
        print(DATA_DICT[ident],arg)
    
    
    for i in range(10):
        t =threading.Thread(target=func,args=(i,))
        t.start()
    

    3.拓展

    import time
    import threading
    
    INFO = {}
    
    
    class Local(object):
    
        def __getattr__(self, item):
            ident = threading.get_ident()
            return INFO[ident][item]
    
        def __setattr__(self, key, value):
            ident = threading.get_ident()
            if ident in INFO:
                INFO[ident][key] = value
            else:
                INFO[ident] = {key: value}
    
    # 实例化
    obj = Local()
    
    
    def func(arg):
        # 调用对象的 __setattr__方法(“phone”,1)
        obj.phone = arg
        time.sleep(2)
        print(obj.phone, arg)
    
    
    if __name__ == '__main__':
        for i in range(10):
            t = threading.Thread(target=func, args=(i,))
            t.start()
    

    总结:
    1.obj.x 调用方法__getattr__
    2.obj.x = 6 调用方法__setattr__

    4.作用

    内部自动为每个线程维护一个空间(字典),用于当前存取属于自己的值。保证线程之间的数据隔离。
    {
    线程ID: {...}
    线程ID: {...}
    线程ID: {...}
    线程ID: {...}
    }

  • 相关阅读:
    java纯数字加密解密实例
    C++手稿:std::string
    java裁剪图片
    java打开windows系统的浏览器
    Android手机无线adb
    office-word
    设计模式-享元模式(13)
    设计模式-外观模式(12)
    charles工具过滤腾讯视频播放器广告
    js将json格式的list转换为按某个字段分组的map数组
  • 原文地址:https://www.cnblogs.com/apollo1616/p/10350959.html
Copyright © 2011-2022 走看看