Python多執行緒下的變數問題
阿新 • • 發佈:2019-02-08
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物件,不能共享。
如果用一個全域性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的程式碼有點醜。
有沒有更簡單的方式?
ThreadLocal應運而生,不用查詢dict,ThreadLocal幫你自動做這件事:
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()
執行結果:
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請求,使用者身份資訊等,這樣一個執行緒的所有呼叫到的處理函式都可以非常方便地訪問這些資源。