Python多執行緒變數優化—threadLocal
阿新 • • 發佈:2018-11-11
Python多執行緒變數優化—threadLocal
再多執行緒的環境下,每個執行緒都有自己的資料。在多執行緒程式設計中應該儘量使用區域性變數,避免使用全域性變數(全域性變數需要加鎖處理)。使用全域性變數時還要考慮變數能不能被共享。
但是使用區域性變數需要在每個函式作為引數傳遞,很麻煩。
threadLocal就是用來解決多執行緒中使用區域性變數導致使用繁瑣的問題。
我們實現一個類似物件工廠的執行緒,上層只需要匯入相關引數,即可生成符合要求的物件。
'多執行緒變數優化,單個執行緒只是用當前執行緒的變數'
'一個ThreadLocal變數雖然是全域性變數,但每個執行緒都只能讀寫自己執行緒的獨立副本' \
',互不干擾。ThreadLocal解決了引數在一個執行緒中各個函式之間互相傳遞的問題。'
__author__ = 'click'
__date__ = '2018/7/24 下午5:44'
import threading
# 1.初始化一個threadLocal
threadLocal = threading.local()
class Student(object):
def __init__(self, name):
self.__name = name
def __str__(self):
return 'Student的屬性__name的值是 %s' % (self.__name)
# 直接使用str會打印出該物件的記憶體地址,不能打印出上述格式化的內容,必須呼叫__repr__代替__str__
__repr__ = __str__
def addStudent():
# 取出資料,threadLocal.studentName 很重要!!!
student = threadLocal.studentName
print('當前執行緒是%1s,該執行緒是用的變數student值是%2s' % (threading.current_thread().name, student.__repr__))
def addStudentThread(name):
# 根據傳遞的引數,建立相關物件
# 往threadLocal 中新增資料
threadLocal.studentName = Student(name)
addStudent()
print('----------使用了threadlocal-------------')
thread1 = threading.Thread(target=addStudentThread, args=('Jack',))
thread2 = threading.Thread(target=addStudentThread, args=('Tom',))
thread1.start()
thread2.start()
thread2.join()
thread1.join()
執行結果:
----------使用了threadlocal-------------
當前執行緒是Thread-1,該執行緒是用的變數student值是<bound method Student.__str__ of Student的屬性__name的值是 Jack>
當前執行緒是Thread-2,該執行緒是用的變數student值是<bound method Student.__str__ of Student的屬性__name的值是 Tom>
使用threadLocal只要分三步:
前提是匯入了threading包
import threading
- 初始化threadLocal
threadLocal = threading.local()
- 向threadLocal變數中賦值
threadLocal.studentName = Student(name)
- 根據變數取出相應的值
student = threadLocal.studentName
三部完成即可使用threadLocal,由於多執行緒中每個執行緒的threadLocal是相互獨立的。因此,在多執行緒的變數優化中,使用threadLocal進行優化是一個很好的選擇。
還有方式可以使用dict進行多執行緒中變數的優化。能夠達到threadLocal相同的功效,只是使用起來比較繁瑣。