threading.local之数据存储隔离

通过Threading的local实现的本地存储隔离

'''

当我们开启多线程来执行func函数,通过自定义的Foo类来存储数据时,我们发现最终的输出结果是全部的线程打印的都是一个最终的数字10,这是因为这样存储的数据线程之间是共享
的,当最后一个线程执行func函数时,由于func函数time.sleep了1秒钟,        
第一个线程还没有来得及打印数据呢,就被最后一个线程传的参数给覆盖了,从而线程们打印的结果都是相同的

'''

import threading
import time


class Foo(object):
    pass


def func(num):
    Foo.num = num
    time.sleep(1)
    print(Foo.num, threading.current_thread().ident)


for i in range(1, 11):
    th = threading.Thread(target=func, args=(i,))
    th.start()

结果
10 35148
10 33584
10 31000
10 34092
10 29248
10 32892
10 30920
10 35180
10 33980
10 35188

flask上下文管理之threading.local

'''

我们使用Threading中的local来存储数据就可以做到数据在线程之间数据隔离。从而就可以理解为什么flask的上下文管理是基于local来实现的数据存储了。

'''
from threading import local
import threading
import time

foo = local()


def func(num):
    foo.num = num
    time.sleep(1)
    print(foo.num, threading.current_thread().ident)


for i in range(1, 11):
    th = threading.Thread(target=func, args=(i,))
    th.start()
结果
2 35340
1 28220
6 35628
7 29948
4 35824
5 31792
3 34848
10 35632
9 28236
8 35068

猜你喜欢

转载自www.cnblogs.com/daviddd/p/11914606.html