python 程序和執行緒之ThreadLocal

2021-09-26 09:02:21 字數 2268 閱讀 8467

python學習筆記,特做記錄,分享給大家,希望對大家有所幫助。

在多執行緒環境下,每個執行緒都有自己的資料。乙個執行緒使用自己的區域性變數比使用全域性變數好,因為區域性變數只有執行緒自己能看見,不會影響其他執行緒,而全域性變數的修改必須加鎖。

但是區域性變數也有問題,就是在函式呼叫的時候,傳遞起來很麻煩:

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)

每個函式一層一層呼叫都這麼傳引數那還得了?用全域性變數?也不行,因為每個執行緒處理不同的student物件,不能共享。

如果用乙個全域性dict存放所有的student物件,然後以thread自身作為key獲得執行緒對應的student物件如何?

global_dict = {}

def std_thread(name):

std = student(name)

# 把std放到全域性變數global_dict中:

global_dict[threading.current_thread()] = std

do_task_1()

do_task_2()

def do_task_1():

# 不傳入std,而是根據當前執行緒查詢:

std = global_dict[threading.current_thread()]

...def do_task_2():

# 任何函式都可以查詢出當前執行緒的std變數:

std = global_dict[threading.current_thread()]

...

這種方式理論上是可行的,它最大的優點是消除了std物件在每層函式中的傳遞問題,但是,每個函式獲取std的**有點醜。

有沒有更簡單的方式?

threadlocal應運而生,不用查詢dict,threadlocal幫你自動做這件事:

import threading

# 建立全域性threadlocal物件:

local_school = threading.local()

def process_student():

std = local_school.student

print 'hello, %s (in %s)' % (std, threading.current_thread().name)

def process_thread(name):

local_school.student = name

process_student()

t1 = threading.thread(target=process_thread, args=('alice',), name='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)

process finished with exit code 0

全域性變數local_school就是乙個threadlocal物件,每個thread對它都可以讀寫student屬性,但互不影響。你可以把local_school看成全域性變數,但每個屬性如local_school.student都是執行緒的區域性變數,可以任意讀寫而互不干擾,也不用管理鎖的問題,threadlocal內部會處理。

可以理解為全域性變數local_school是乙個dict,不但可以用local_school.student,還可以繫結其他變數,如local_school.teacher等等。

threadlocal最常用的地方就是為每個執行緒繫結乙個資料庫連線,http請求,使用者身份資訊等,這樣乙個執行緒的所有呼叫到的處理函式都可以非常方便地訪問這些資源。

JAVA多執行緒之Runnable和Thread比較

在我們開發的過程中常常會碰到多執行緒的問題,對於多執行緒的實現方式主要有兩種 實現runnable介面 繼承thread類。對於這兩種多執行緒的實現方式也是有著一些差異。既然實現了多執行緒那必然離不開管理這些執行緒,當問題比簡單時乙個或者幾個執行緒就ok了,也涉及不到效率問題。一旦執行緒數量多起來的...

Python程序和執行緒之間的關係

程序是由執行緒組成的 程序之間全域性變數不共享 執行緒之間資源共享 程序和執行緒的執行是無序的 程序和執行緒的執行是無序的 from multiprocessing import from time import from threading import def print info sleep ...

執行緒之間和程序之間的同步

今天學習的內容為 利用互斥事件來控制線程之間 程序之間的同步問題。其實,程序之間的同步也就類似於執行緒之間的同步。互斥事件的作用就是為了保證任乙個時間內,只有乙個執行緒對對公共資源進行操作。下面來看一下執行緒之間的同步,如果是在乙個程序內的執行緒同步問題的話。這樣的例子很多,我就舉乙個最簡單的,執行...