進程和線程(3)-ThreadLocal

ThreadLocal

在多線程環境下,每一個線程都有本身的數據。一個線程使用本身的局部變量比使用全局變量好,由於局部變量只有線程本身能看見,不會影響其餘線程,而全局變量的修改必須加鎖。python

可是局部變量也有問題,就是在函數調用的時候,傳遞起來很麻煩:數據庫

def process_student(name): std = Student(name) # std是局部變量,可是每一個函數都要用它,所以必須傳進去: do_task_1(std) do_task_2(std) def do_task_1(std): do_subtask_1(std) do_subtask_2(std) def do_task_2(std): do_subtask_2(std) do_subtask_2(std) 

每一個函數一層一層調用都這麼傳參數那還得了?用全局變量?也不行,由於每一個線程處理不一樣的Student對象,不能共享。ruby

若是用一個全局dict存放全部的Student對象,而後以thread自身做爲key得到線程對應的Student對象如何?多線程

global_dict = {}

def std_thread(name): std = Student(name) # 把std放到全局變量global_dict中: global_dict[threading.current_thread()] = std do_task_1() do_task_2() def do_task_1(): # 不傳入std,而是根據當前線程查找: std = global_dict[threading.current_thread()] ... def do_task_2(): # 任何函數均可以查找出當前線程的std變量: std = global_dict[threading.current_thread()] ... 

這種方式理論上是可行的,它最大的優勢是消除了std對象在每層函數中的傳遞問題,可是,每一個函數獲取std的代碼有點醜。函數

有沒有更簡單的方式?spa

ThreadLocal應運而生,不用查找dictThreadLocal幫你自動作這件事:線程

import threading # 建立全局ThreadLocal對象: local_school = threading.local() def process_student(): print 'Hello, %s (in %s)' % (local_school.student, threading.current_thread().name) def process_thread(name): # 綁定ThreadLocal的student: local_school.student = name process_student() t1 = threading.Thread(target= process_thread, args=('Alice',), name='Thread-A') t2 = threading.Thread(target= process_thread, args=('Bob',), name='Thread-B') t1.start() t2.start() t1.join() t2.join() 

執行結果:code

Hello, Alice (in Thread-A) Hello, Bob (in Thread-B) 

全局變量local_school就是一個ThreadLocal對象,每一個Thread對它均可以讀寫student屬性,但互不影響。你能夠把local_school當作全局變量,但每一個屬性如local_school.student都是線程的局部變量,能夠任意讀寫而互不干擾,也不用管理鎖的問題,ThreadLocal內部會處理。對象

能夠理解爲全局變量local_school是一個dict,不但能夠用local_school.student,還能夠綁定其餘變量,如local_school.teacher等等。資源

ThreadLocal最經常使用的地方就是爲每一個線程綁定一個數據庫鏈接,HTTP請求,用戶身份信息等,這樣一個線程的全部調用到的處理函數均可以很是方便地訪問這些資源。

相關文章
相關標籤/搜索