天天看點

多線程下的threadLocal

多線程下的threadLocal

# 問題:
	flask中,不同的請求即不同的線程,它們共用一個全局的request對象,為什麼不會亂?

# 解答:
	多線程下的threadLocal
           
特别鳴謝:
	https://blog.csdn.net/youcijibi/article/details/113772990
           

threadLocal介紹

# 定義:
	threadLocal變量是一個全局變量,但每個線程都隻能讀寫自己線程的獨立副本,互不幹擾。用來解決了參數在一個線程中各個函數之間互相傳遞的問題

           
# demo
import threading
import time
 
# 建立全局ThreadLocal對象
local_school = threading.local()
 
 
def process_student():
    # 擷取目前線程關聯定義的student
    std = local_school.student
    print('hello %s in (%s)' % (std, threading.current_thread().getName()))
 
 
def process_thread(name):
    # 綁定thread_local的student
    local_school.student = name
    # 如果沒有threading.local那麼需要給函數傳遞變量參數才行,或者寫入到全局的字典中,有些low
    # global_dict = {}
    # global_dict[threading.current_thread()] = name
    process_student()
 
 
if __name__ == '__main__':
    t1 = threading.Thread(target=process_thread, args=('老李',), name='Thread-A')
    t2 = threading.Thread(target=process_thread, args=('老王',), name='Thread-B')
    t1.start()
    t2.start()
           
# 解析
	上例中:local_school是全局的,但每個線程去通路都不一樣,flask中的session就類似于local_school。
           

繼續閱讀