Python編程:threading多線程之ThreadLocal
發(fā)布時(shí)間:2021-11-23 點(diǎn)擊數(shù):722
一個(gè)ThreadLocal變量雖然是全局變量,但每個(gè)線程都只能讀寫自己線程的獨(dú)立副本,互不干擾。ThreadLocal解決了參數(shù)在一個(gè)線程中各個(gè)函數(shù)之間互相傳遞的問(wèn)題。
代碼示例
# -*- coding: utf-8 -*- # @File : thread_local_demo.py # @Date : 2018-06-11 # @Author : Peng Shiyu import threading # 創(chuàng)建全局ThreadLocal對(duì)象 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編程:排序算法之冒泡排序 下一篇:框架畫(huà)Button的入口
