threading.local 代码笔记

演示局部变量

import threading
import time

def 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 = 0

def 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是不能跨线程的
# 所以在启子线程的时候,重新访问这个变量的时候会抛出异常

猜你喜欢

转载自blog.51cto.com/windchasereric/2355011
今日推荐