首页 > 其他 > 详细

threading.local 代码笔记

时间:2019-02-26 15:42:50      阅读:169      评论:0      收藏:0      [点我收藏+]
演示局部变量
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是不能跨线程的
# 所以在启子线程的时候,重新访问这个变量的时候会抛出异常

threading.local 代码笔记

原文:https://blog.51cto.com/windchasereric/2355011

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!