threading.local
import time
import threading
class Foo(object):
def __init__(self):
self.num = 0
val2 = Foo()
def task(i):
val2.num = i
time.sleep(1)
print(val2.num)
for i in range(4):
t = threading.Thread(target=task,args=(i,))
t.start()
# 3
# 3
# 3
# 3
import time
import threading
# 当每个线程在执行 val1.xx=1 ,在内部会为此线程开辟一个空间,来存储 xx=1
# val1.xx,找到此线程自己的内存地址去取自己存储 xx
# 其实就是通过线程ID进行标记
val1 = threading.local()
def task(i):
val1.num = i
time.sleep(1)
print(val1.num)
for i in range(4):
t = threading.Thread(target=task,args=(i,))
t.start()
# 0
# 2
# 1
# 3