做网站需要懂什么技术,网站推广方法是什么,朋友圈推广广告,南山网站建设哪家便宜前段时间看了下flask的源码#xff0c;对于这样一个轻量级的web框架是怎样支持多线程的感到非常好奇#xff0c;于是深入了解了一番。flask是依赖werkeug来实现线程间的隔离的#xff0c;而werkeug最后又使用到了python的内置模块locals来承载数据#xff0c;看不如写…前段时间看了下flask的源码对于这样一个轻量级的web框架是怎样支持多线程的感到非常好奇于是深入了解了一番。flask是依赖werkeug来实现线程间的隔离的而werkeug最后又使用到了python的内置模块locals来承载数据看不如写于是自己实现了一下。from threading importcurrentThread, Threadfrom collections importdefaultdictimportsysclassLocalProxy(object):def __init__(self):self.localdefaultdict(dict)def __repr__(self):returnstr(self.local)def __str__(self):returnstr(self.local)def __getitem__(self, item):returnself.local[currentThread().ident][item]def __setitem__(self, key, value):self.local[currentThread().ident].update({key: value})print(sys.version)local_proxyLocalProxy()print(local_proxy)local_proxy[main] startdefchange_property():local_proxy[main] endchange_thread Thread(targetchange_property)change_thread.daemonTruechange_thread.start()change_thread.join()print(local_proxy)输出3.7.3 (default, Mar 27 2019, 17:13:21) [MSC v.1915 64bit (AMD64)]defaultdict(, {})defaultdict(, {7092: {‘main‘: ‘start‘}, 4892: {‘main‘: ‘end‘}})这里是使用locals来作为数据承载的dict然后使用currentThread方法获取当前线程id以此作为key来实现各线程间的数据隔离。从输出可以看出主线程设置了mainstart后子线程对该属性进行修改并未成功而是在自己的线程id下创建了新的属性。实现过程中还发生了一个小插曲当时的开启线程代码如下change_thread Thread(change_property)change_thread.daemonTruechange_thread.start()报错Traceback (most recent call last):3.7.3 (default, Mar 27 2019, 17:13:21) [MSC v.1915 64bit (AMD64)]defaultdict(, {})FileE:/project/blog/blog/src/utils/local_.py, line 34, in change_threadThread(change_property)FileD:UsersAdministratorAnaconda3libhreading.py, line 781, in __init__assert group is None, group argument must be None for nowAssertionError: group argument must be Nonefor now于是点开Thread源码看看这个group为何物def __init__(self, groupNone, targetNone, nameNone,args(), kwargsNone, *, daemonNone):This constructor should always be called with keyword arguments. Arguments are:*group* should be None; reserved for future extension when a ThreadGroupclass is implemented.原来Thread的初始化增加了group参数切对其进行了断言为以后即将实现的ThreadGroup铺路。ps 以后传参还是尽量带上参数名。Python的线程隔离实现方法