python3 线程隔离_Python的线程隔离实现方法
前段時間看了下flask的源碼,對于這樣一個輕量級的web框架是怎樣支持多線程的感到非常好奇,于是深入了解了一番。
flask是依賴werkeug來實現線程間的隔離的,而werkeug最后又使用到了python的內置模塊locals來承載數據,看不如寫,于是自己實現了一下。
from threading importcurrentThread, Threadfrom collections importdefaultdictimportsysclassLocalProxy(object):def __init__(self):
self.local=defaultdict(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_proxy=LocalProxy()print(local_proxy)
local_proxy["main"] = "start"
defchange_property():
local_proxy["main"] = "end"change_thread= Thread(target=change_property)
change_thread.daemon=True
change_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來實現各線程間的數據隔離。
從輸出可以看出,主線程設置了`main=start`后,子線程對該屬性進行修改并未成功,而是在自己的線程id下創建了新的屬性。
實現過程中還發生了一個小插曲,當時的開啟線程代碼如下:
change_thread =Thread(change_property)
change_thread.daemon=True
change_thread.start()
報錯:
Traceback (most recent call last):3.7.3 (default, Mar 27 2019, 17:13:21) [MSC v.1915 64bit (AMD64)]
defaultdict(, {})
File"E:/project/blog/blog/src/utils/local_.py", line 34, in change_thread=Thread(change_property)
File"D:UsersAdministratorAnaconda3libhreading.py", line 781, in __init__
assert group is None, "group argument must be None for now"AssertionError: group argument must be Nonefor now
于是點開Thread源碼看看這個group為何物:
def __init__(self, group=None, target=None, name=None,
args=(), kwargs=None, *, daemon=None):"""This constructor should always be called with keyword arguments. Arguments are:
*group* should be None; reserved for future extension when a ThreadGroup
class is implemented.
原來Thread的初始化增加了group參數,切對其進行了斷言,為以后即將實現的ThreadGroup鋪路。
ps:?以后傳參還是盡量帶上參數名。
Python的線程隔離實現方法
總結
以上是生活随笔為你收集整理的python3 线程隔离_Python的线程隔离实现方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ddos攻击动画(ddos 攻击动画)
- 下一篇: python单元测试mock_Mock