Python學習筆記__10.3章 ThreadLocal
1、概覽
在多線程環境下,每個線程都有自己的數據。一個線程使用自己的局部變量比使用全局變量好,因為局部變量只有線程自己能看見,不會影響其他線程,而全局變量的修改必須加鎖。但線程的局部變量,在函數調用時很麻煩
1)方式一:一層一層傳
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)
2)方式二:用一個全局dict存放所有的Student對象,然後以thread自身作為key獲得線程對應的Student對象
global_dict = {}
def std_thread(name):
std = Student(name)
global_dict[threading.current_thread()] = std # 以thread自身作為key,把std放到全局變量global_dict中
do_task_1()
do_task_2()
def do_task_1():
std = global_dict[threading.current_thread()] # 不傳入std,而是根據當前線程查找
def do_task_2()
std = global_dict[threading.current_thread()] # 任何函數都可以查找出當前線程的std變量
3)方式三:ThreadLocal
import threading
local_school = threading.local() # 創建全局ThreadLocal對象
def process_student():
std = local_school.student # 獲取當前線程綁定在student的變量
print('Hello, %s (in %s)' % (std, threading.current_thread().name))
def process_thread(name):
local_school.student = name # 為ThreadLocal加student屬性,綁定線程變量
process_student() # 調用函數
t1 = threading.Thread(target= process_thread, args=('Alice',), name='Thread-A') #創建線程,線程名為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對象。可以把它看成全局變量。任何線程綁定變量在它的不同屬性上。以達成互不幹擾的效果
2、小結
ThreadLocal最常用的地方就是為每個線程綁定一個數據庫連接,HTTP請求,用戶身份信息等,這樣一個線程的所有調用到的處理函數都可以非常方便地訪問這些資源。
一個ThreadLocal變量雖然是全局變量,但每個線程都只能讀寫自己線程的獨立副本,互不幹擾。ThreadLocal解決了參數在一個線程中各個函數之間互相傳遞的問題。
Python學習筆記__10.3章 ThreadLocal