演示局部变量

import threadingimport timedef worker(): x = 0 for i in range(100): time.sleep(0.0001) x += 1 print(threading.current_thread(), x)for i in range(3): threading.Thread(target=worker).start()测试使用全局变量

class A: def __init__(self): self.x = 0def worker(): global_data.x = 0 for i in range(100): time.sleep(0.0001) global_data.x += 1 print(threading.current_thread(), global_data.x)for i in range(3): threading.Thread(target=worker).start()# 测试发现结果不是我们期望的那样引入threading.local

将全局变量,变换成线程的局部变量

global_data = threading.local()def worker(): global_data.x = 0 for i in range(100): time.sleep(0.0001) # x += 1 global_data.x += 1 print(threading.current_thread(), global_data.x)for i in range(3): threading.Thread(target=worker).start()演示threading.local不能跨线程的问题

X = 'abc'ctx = threading.local()ctx.x = 123 # 留意下这一句print(ctx, type(ctx), ctx.x)def worker(): print(X) print(ctx) # ctx.x = '11111' # 注释掉这一行,会报错。去掉注释在执行一次 print(ctx.x) print('working')worker()print('========')threading.Thread(target=worker).start()# 第三行,因为这个变量在定义的时候是在当前线程下,而threading.local是不能跨线程的# 所以在启子线程的时候,重新访问这个变量的时候会抛出异常