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: {...}
}