Flask中的ThreadLocal本地线程,上下文管理

先说一下和flask没有关系的:

我们都知道线程是由进程创建出来的,CPU实际执行的也是线程,那么线程其实是没有自己独有的内存空间的,所有的线程共享进程的资源和空间,共享就会有冲突,对于多线程对同一块数据处理的冲突问题,一个办法就是加互斥锁,另一个办法就是利用threadlocal

ThreadLocal   实现的思路就是给一个进程中的多个线程开辟空间来保存线程中特有的值

代码实现:

1、简单示例:

复制代码
import threading
# 实例化对象
local_values = threading.local()
def func(num):
    # 给对象加属性,这个属性就会保存在当前线程开辟的空间中
    local_values.name = num
    import time
    time.sleep(1)
    # 取值的时候也从当前线程开辟的空间中取值
    print(local_values.name, threading.current_thread().name)
for i in range(20):
    th = threading.Thread(target=func, args=(i,), name='线程%s' % i)
    th.start()
复制代码

打印结果:

复制代码
0 线程0
1 线程1
2 线程2
3 线程3
10 线程10
9 线程9
4 线程4
8 线程8
5 线程5
7 线程7
6 线程6
13 线程13
11 线程11
17 线程17
15 线程15
14 线程14
16 线程16
12 线程12
18 线程18
19 线程19
复制代码

如果把对象换成一个类对象:

复制代码
import threading
# 如果是一个类对象,结果就完全不一样
 class Foo(object):
     def __init__(self):
         self.name = 0
local_values = Foo()
def func(num):
    local_values.name = num
    import time
    time.sleep(1)
    print(local_values.name, threading.current_thread().name)
for i in range(20):
    th = threading.Thread(target=func, args=(i,), name='线程%s' % i)
    th.start()
复制代码

打印结果:

复制代码
19 线程1
19 线程3
19 线程4
19 线程5
19 线程2
19 线程0
19 线程9
19 线程6
19 线程8
19 线程11
19 线程7
19 线程10
19 线程15
19 线程16
19 线程13
19 线程14
19 线程18
19 线程19
19 线程12
19 线程17
复制代码

2、依据这个思路,我们自己实现给线程开辟独有的空间保存特有的值

协程和线程都有自己的唯一标识get_ident,利用这个唯一标识作为字典的key,key对应的value就是当前线程或协程特有的值,取值的时候也拿这个key来取

复制代码
import threading
# get_ident就是获取线程或协程唯一标识的
try:
    from greenlet import getcurrent as get_ident # 协程
    # 当没有协程的模块时就用线程
except ImportError:
    try:
        from thread import get_ident
    except ImportError:
        from _thread import get_ident # 线程
class Local(object):
    def __init__(self):
        self.storage = {}
        self.get_ident = get_ident
    def set(self,k,v):
        ident = self.get_ident()
        origin = self.storage.get(ident)
        if not origin:
            origin = {k:v}
        else:
            origin[k] = v
        self.storage[ident] = origin
    def get(self,k):
        ident = self.get_ident()
        origin = self.storage.get(ident)
        if not origin:
            return None
        return origin.get(k,None)
# 实例化自定义local对象对象
local_values = Local()
def task(num):
    local_values.set('name',num)
    import time
    time.sleep(1)
    print(local_values.get('name'), threading.current_thread().name)
for i in range(20):
    th = threading.Thread(target=task, args=(i,),name='线程%s' % i)
    th.start()
复制代码

3、因为要不停的赋值取值,就想到了__setattr__和__getattr__方法,但是要注意初始化时赋值和__setattr__方法中赋值又可能产生递归的问题

复制代码
import threading
try:
    from greenlet import getcurrent as get_ident # 协程
except ImportError:
    try:
        from thread import get_ident
    except ImportError:
        from _thread import get_ident # 线程
class Local(object):
    def __init__(self):
        # 这里一定要用object来调用,因为用self调用的就会触发__setattr__方法,__setattr__方法里
        # 又会用self去赋值就又会调用__setattr__方法,就变成递归了
        object.__setattr__(self, '__storage__', {})
        object.__setattr__(self, '__ident_func__', get_ident)
    def __getattr__(self, name):
        try:
            return self.__storage__[self.__ident_func__()][name]
        except KeyError:
            raise AttributeError(name)
    def __setattr__(self, name, value):
        ident = self.__ident_func__()
        storage = self.__storage__
        try:
            storage[ident][name] = value
        except KeyError:
            storage[ident] = {name: value}
    def __delattr__(self, name):
        try:
            del self.__storage__[self.__ident_func__()][name]
        except KeyError:
            raise AttributeError(name)
local_values = Local()
def task(num):
    local_values.name = num
    import time
    time.sleep(1)
    print(local_values.name, threading.current_thread().name)
for i in range(20):
    th = threading.Thread(target=task, args=(i,),name='线程%s' % i)
    th.start()
复制代码

我们再说回Flask,我们知道django中的request是直接当参数传给视图的,这就不存在几个视图修改同一个request的问题,但是flask不一样,flask中的request是导入进去的,就相当于全局变量,每一个视图都可以对它进行访问修改取值操作,这就带来了共享数据的冲突问题,解决的思路就是我们上边的第三种代码,利用协程和线程的唯一标识作为key,也是存到一个字典里,类中也是采用__setattr__和__getattr__方法来赋值和取值

分情况:

对于单进程单线程:没有影响,基于全局变量

对于单进程多线程:利用threading.local()  对象

对于单进程单线程的多协程:本地线程对象就做不到了,要用自定义,就是上边的第三个代码

一共涉及到四个知识点:

1、唯一标识

2、本地线程对象

3、setattr和getattr

4、怎么实现

猜你喜欢

转载自www.cnblogs.com/ExMan/p/9851768.html