python語言線程標準庫threading.local解讀總結

本段源碼可以學習的地方:

  1. 考慮到效率問題,可以通過上下文的機制,在屬性被訪問的時候臨時構建;

  2. 可以重寫一些魔術方法,比如 new 方法,在調用 object.new(cls) 前後進行屬性的一些小設置;

  3. 在本庫中使用的重寫魔術方法,上下文這兩種基礎之上,我們可以想到函數裝飾器,類裝飾器,異常捕獲,以及兩種上下文的結構;

靈活運用這些手法,可以讓我們在代碼架構上更上一層,能夠更加省時省力。

from weakref import ref # ref用在了構造大字典元素元組的第一個位置即 (ref(Thread), 線程字典)
from contextlib import contextmanager # 上下文管理,用來確保__dict__屬性的存在
from threading import current_thread, RLock
__all__ = ["local"]
 
class _localimpl: # local()._local__impl = _localimpl() # local()實例的屬性_local__impl就是這個類的實例
  """一個管理線程字典的類"""
  __slots__ = 'key', 'dicts', 'localargs', 'locallock', '__weakref__' # _local__impl有這麼多屬性
 
  def __init__(self):
    # 這個self.key是用在線程對象的字典中的key
    # self.key使用的一個字符串,這樣既能運行的快,
    # 但是通過'_threading_local._localimpl.' + str(id(self)也能保證不會衝突別的屬性
 
    self.key = '_threading_local._localimpl.' + str(id(self))
    #
    self.dicts = {} # 大字典
    # 格式是: { id(線程1):(ref(Thread), 線程1自身的字典), id(線程2):(ref(Thread), 線程2自身的字典), ... }
 
  def get_dict(self): # 從大字典中拿(ref(Thread), 線程字典), 然後取線程字典
    thread = current_thread()
    return self.dicts[id(thread)][1]
 
  def create_dict(self): # 爲當前線程創建一個線程字典,就是(ref(Thread), 線程字典)[1],即元組的第二部分
    localdict = {}
    key = self.key # key使用'_threading_local._localimpl.' + str(id(self)
    thread = current_thread() # 當前線程
    idt = id(thread) # 當前線程的id
    def local_deleted(_, key=key): # 這個函數不看 pass
      # When the localimpl is deleted, remove the thread attribute.
      thread = wrthread()
      if thread is not None:
        del thread.__dict__[key]
    def thread_deleted(_, idt=idt): # 這個函數不看 pass
      # When the thread is deleted, remove the local dict.
      # Note that this is suboptimal if the thread object gets
      # caught in a reference loop. We would like to be called
      # as soon as the OS-level thread ends instead.
      local = wrlocal()
      if local is not None:
        dct = local.dicts.pop(idt)
    wrlocal = ref(self, local_deleted)
    wrthread = ref(thread, thread_deleted) # 大字典中每一個線程對應的元素的第一個位置: (ref(Thread), 小字典)
    thread.__dict__[key] = wrlocal
    self.dicts[idt] = wrthread, localdict # 在大字典中構造: id(thread) : (ref(Thread), 小字典)
    return localdict
 
 
@contextmanager
def _patch(self):
  impl = object.__getattribute__(self, '_local__impl') # 此時的self是local(), 拿local()._local__impl
  try:
    dct = impl.get_dict()  # 然後從拿到的local()._local__impl調用線程字典管理類的local()._local__impl.get_dict()方法
                # 從20行到22這個get_dict()方法的定義可以看出來,拿不到會報KeyError的
 
  except KeyError: # 如果拿不到報 KeyError之後捕捉
    dct = impl.create_dict() # 然後再通過線程字典管理類臨時創建一個
    args, kw = impl.localargs # 這個時候把拿到
    self.__init__(*args, **kw)
  with impl.locallock: # 通過上下文的方式上鎖
    object.__setattr__(self, '__dict__', dct) # 給local() 實例增加__dict__屬性,這個屬性指向大字典中value元組的第二個元素,即線程小字典
    yield # 到目前爲止,local()類的兩個屬性都構造完成
 
 
class local: # local類
  __slots__ = '_local__impl', '__dict__' # local類有兩個屬性可以訪問
 
  def __new__(cls, *args, **kw):
    if (args or kw) and (cls.__init__ is object.__init__): # pass不看
      raise TypeError("Initialization arguments are not supported")
    self = object.__new__(cls) # pass不看
    impl = _localimpl() # _local_impl屬性對應的是_localimpl類的實例
    impl.localargs = (args, kw) # _local_impl屬性即_localimpl類的實例 的 localargs屬性是一個元組
    impl.locallock = RLock() # pass 不看
    object.__setattr__(self, '_local__impl', impl)
    # 把_local__impl 增加給local(), 所以:local()._local__impl is ipml 即 _localimp()
 
    # __slots__規定了local()有兩個屬性,這裏已經設置了一個_local__impl;
    # 第二個屬性__dict__當我們以後在訪問的時候使用上下文進行臨時增加,比如第85行
 
    impl.create_dict() # 就是local._local__impl.create_dict()
    return self # 返回這個配置好_local__impl屬性的local()實例
 
  def __getattribute__(self, name): # 當我們取local()的屬性時
    with _patch(self): # 會通過上下文先把數據準備好
      return object.__getattribute__(self, name) # 在準備好的數據中去拿要拿的屬性name
 
  def __setattr__(self, name, value):
    if name == '__dict__': # 這個判斷語句是控制local()實例的__dict__屬性只能讀不能被替換
      raise AttributeError(
        "%r object attribute '__dict__' is read-only"
        % self.__class__.__name__)
    with _patch(self): # 同理, 通過上下文先把__dict__構造好
      return object.__setattr__(self, name, value) # 然後調用基類的方法設置屬性
 
  def __delattr__(self, name): # 刪除屬性,同理,和__setattr__手法相似
    if name == '__dict__':  # 這個判斷語句是控制local()實例的__dict__屬性只能讀不能被替換
      raise AttributeError(
        "%r object attribute '__dict__' is read-only"
        % self.__class__.__name__)
    with _patch(self): # 同理, 通過上下文先把__dict__構造好
      return object.__delattr__(self, name)
 
# 整體架構圖:
'''
 
                                        / —— key 屬性
                                       / —— dicts 屬性, 格式{id(Thread):(ref(Thread), 線程小字典)}
            ———— : _local__impl屬性  ---------- 是_local類的實例                           |
           /                             —— 其他屬性...                  |
           /             /—————————————————————————————————————————————————————————————————————————————————/
  創建一個local實例              /
           \            /
           \           /
            ———— : __dict__屬性 -------- 對應的是_local__impl屬性的dicts 中的線程小字典
 
 
 
'''

內容就以上怎麼多,最後給大家推薦一個口碑不錯的公衆號【程序員學府】,這裏有很多的老前輩學習

技巧,學習心得,面試技巧,職場經歷等分享,更爲大家精心準備了零基礎入門資料,實戰項目資料,

每天都有程序員定時講解Python技術,分享一些學習的方法和需要留意的小細節
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章