Python編程:threading多線程之ThreadLocal
發(fā)布時間:2021-11-23 點擊數(shù):626
一個ThreadLocal變量雖然是全局變量,但每個線程都只能讀寫自己線程的獨立副本,互不干擾。ThreadLocal解決了參數(shù)在一個線程中各個函數(shù)之間互相傳遞的問題。
代碼示例
# -*- coding: utf-8 -*- # @File : thread_local_demo.py # @Date : 2018-06-11 # @Author : Peng Shiyu import threading # 創(chuàng)建全局ThreadLocal對象 local_dict = threading.local() def process_item(): # 獲取當(dāng)前線程關(guān)聯(lián)的name name = local_dict.name print("thread: %s name: %s"% (threading.current_thread().name, name)) def process_thread(name): # 綁定ThreadLocal的name local_dict.name = name process_item() t1 = threading.Thread(target=process_thread, args=("Tom",), name="Thread-Tom") t2 = threading.Thread(target=process_thread, args=("Jack",), name="Thread-Jack") t1.start() t2.start() t1.join() t2.join() """ thread: Thread-Tom name: Tom thread: Thread-Jack name: Jack """
上一篇:Python編程:排序算法之冒泡排序 下一篇:框架畫Button的入口