Python的线程隔离实现方法
前段时间看了下flask的源码,对于这样一个轻量级的web框架是怎样支持多线程的感到非常好奇,于是深入了解了一番。
flask是依赖werkeug来实现线程间的隔离的,而werkeug最后又使用到了python的内置模块locals来承载数据,看不如写,于是自己实现了一下。
from threading import currentThread, Thread
from collections import defaultdict
import sys
class LocalProxy(object):
def __init__(self):
self.local = defaultdict(dict)
def __repr__(self):
return str(self.local)
def __str__(self):
return str(self.local)
def __getitem__(self, item):
return self.local[currentThread().ident][item]
def __setitem__(self, key, value):
self.local[currentThread().ident].update({key: value})
print(sys.version)
local_proxy = LocalProxy()
print(local_proxy)
local_proxy["main"] = "start"
def change_property():
local_proxy["main"] = "end"
change_thread = Thread(target=change_property)
change_thread.daemon= True
change_thread.start()
change_thread.join()
print(local_proxy)

![Python的线程隔离实现方法
[编程语言教程]](https://www.zixueka.com/wp-content/uploads/2024/02/1706717074-addb3aca034e43f.jpg)
