在多線程環境下,全域變數需加鎖保護,傳遞區域變數又會導致層層函式呼叫參數繁瑣。若每個線程需維護獨立的資料物件(如使用者會話、資料庫連線),傳統做法是用全域字典以線程物件為鍵,但程式碼不夠優雅。
threading.local() 建立的物件在不同線程中擁有獨立的屬性儲存空間,互不干擾,無需手動管理鎖或字典查找。
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):
# 綁定當前線程專屬的 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.student 在每個線程中都是獨立變數,寫入不影響其他線程。local_school.teacher、local_school.db_conn 等。g、Django 的 request)ThreadLocal 物件本身是全域的,但其屬性是線程隔離的。線程結束時,其對應的 ThreadLocal 儲存會被自動回收(需注意線程池複用場景下的記憶體洩漏風險)。