03 threading.local和高级

1.python之threading.local

  • 当每个线程在执行 val.num=1 ,在内部会为此线程开辟一个空间,来存储 num=1

  • val.num,找到此线程自己的内存地址去取自己存储 num

    import time
    import threading
    
    val1 = threading.local()
    
    def task(i):
        val.num = i
        time.sleep(1)
        print(val.num)
    
    for i in range(4):
        t = threading.Thread(target=task,args=(i,))
        t.start()

2. 线程唯一标识

  • get_ident

    import threading
    from threading import get_ident
    
    def task():
        ident = get_ident()
        print(ident)
    for i in range(20):
        t = threading.Thread(target=task)
        t.start()

3. 自定义threading.local

  • 储存结构:

    storage = {
    1112:{'x1':1}
    1113:{'x1':2}
    1114:{'x1':3}
    1115:{'x1':4}
    }

    import threading
    class Local(object):
        def __init__(self):
            object.__setattr__(self,'storage',{})
    
        def __setattr__(self, key, value):
            ident = threading.get_ident()
            if ident in self.storage:
                self.storage[ident][key] = value
            else:
                self.storage[ident] = {key:value}
    
        def __getattr__(self, item):
            ident = threading.get_ident()
            if ident not in self.storage:
                return
            return self.storage[ident].get(item)
    
    local = Local()
    
    def task(arg):
        local.x1 = arg
        print(local.x1)
    
    for i in range(5):
        t = threading.Thread(target=task,args=(i,))
        t.start()

4. 加强版threading.local

  • 储存结构:

    storage = {
    1111:{'x1':[]},
    1112:{'x1':[]}
    1113:{'x1':[]}
    1114:{'x1':[]}
    1115:{'x1':[]},
    1116:{'x1':[]}
    }

    import threading
    class Local(object):
        def __init__(self):
            object.__setattr__(self,'storage',{})
    
        def __setattr__(self, key, value):
            ident = threading.get_ident()
            if ident in self.storage:
                self.storage[ident][key].append(value)
            else:
                self.storage[ident] = {key:[value,]}
    
        def __getattr__(self, item):
            ident = threading.get_ident()
            if ident not in self.storage:
                return
            return self.storage[ident][item][-1]
    
    local = Local()
    
    def task(arg):
        local.x1 = arg
        print(local.x1)
    
    for i in range(5):
        t = threading.Thread(target=task,args=(i,))
        t.start()
12-29 22:50