先说一下和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、怎么实现

最新文章

  1. opencv源码阅读之——iOS的两条接口UIImageToMat()和MatToUIImage()
  2. warning C4005: “AF_IPX”: 宏重定义的解决办法
  3. Dynamics AX 2012 R3 Demo 安装与配置 - 导入测试数据 (Step 4)
  4. 由struts错误使用引发的漏洞,使用参数作为返回的文件路径或文件名,作为返回result 值
  5. node.js EventEmitter发送和接收事件
  6. 模仿ios下的coverflow
  7. 【问题】tableView的每组的头部不不能滚动的解决方案
  8. Bootstrap Modal 垂直居中
  9. 25个最佳最闪亮的Eclipse开发项目
  10. javascript模块化编程库require.js的用法
  11. Unity热更新之C#反射动态获取类属性及方法
  12. OsharpNS轻量级.net core快速开发框架简明入门教程-基于Osharp实现自己的业务功能
  13. .NET Standard 2.0正式发布了
  14. FineUILearning
  15. python - 练习统计随机字母数据
  16. 部署前准备--使用Mysql之Django Debug Toolbar安装以及配置
  17. .Net Core缓存组件(Redis)源码解析
  18. [LeetCode&Python] Problem 268. Missing Number
  19. Linux 网络命令找不到
  20. Spring Boot中Starter是什么

热门文章

  1. Centos6.5下 执行“ll”提示“-bash: ll: command not found”
  2. 安装Vmware Tools出现错误
  3. Bootstrap-Table 总结
  4. Python之Pycharm安装及介绍
  5. 基于vue实现模糊匹配(这里以邮箱模糊匹配为例,其他的模糊匹配都可以类比)
  6. 有趣的鼠标悬浮模糊效果总结---(filter,渐变文字)
  7. 测试各种低价VPS
  8. noip模拟赛 将军令
  9. 网络编程基础:粘包现象、基于UDP协议的套接字
  10. Linux下汇编语言学习笔记24 ---