多线程threading.local的作用?

时间:2019-02-03 20:46:30   收藏:0   阅读:252

1.作用:

内部自动为每个线程维护一个空间(字典),用于当前存取属于自己的值.保证线程之间的数据隔离.
{
    线程ID: {...}
    线程ID: {...}
    线程ID: {...}
    线程ID: {...}
}
    

2.示例:

import time
import threading

v = threading.local()


def func(arg):
    # 内部会为当前线程创建一个空间用于存储:phone=自己的值
    v.phone = arg
    time.sleep(2)
    # 去当前线程自己空间取值
    print(v.phone, arg)


for i in range(10):
    t = threading.Thread(target=func, args=(i,))
    t.start()

原文:https://www.cnblogs.com/apollo1616/p/10350959.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!