利用flask上下文管理原理,实现线程之间的数据安全
由于一般的程序基本上都是IO密集型,如果只是为了保证数据的安全而去开启进程,这必定是浪费资源的行为;为了保证数据的安全,借用flask的上下文的原理,如下代码实现
from threading import Thread
import time
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__方法,就变成递归,最后循环调用,最后报错
# __setattr__添加/修改属性会触发它的执行
# __delattr__删除属性的时候会触发
# __getattr__只有在使用点调用属性且属性不存在的时候才会触发
object.__setattr__(self, '__storage__', {})
object.__setattr__(self, '__ident_func__', get_ident)
self.i = 0
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 demo1_process():
local_values.i = 1
time.sleep(1)
print(local_values.i)
def demo2_process():
local_values.i = 2
time.sleep(1)
print(local_values.i)
def run():
print("start:")
t = Thread(target=demo1_process)
t.start()
t1 = Thread(target=demo2_process)
t1.start()
run()