温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

threading.local 代码笔记

发布时间:2020-06-26 09:49:17 来源:网络 阅读:215 作者:windcharger 栏目:编程语言

演示局部变量

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

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI