Python-線程內的全局變量


標准庫的threading有一個local對象,可以實現如flask的g對象(session, request)一樣, 線程內的全局變量。

即方便了數據的傳輸,同時使線程間數據相互獨立,簡單示例:

# coding:utf-8
import threading
import time

local_data = threading.local()

def decorator(fun):
    def wrapper(*args):
        local_data.g = threading.currentThread()
        return fun(*args)
    return wrapper

@decorator
def fun1():
    print "fun1 running..."
    time.sleep(1)
    print "local data: ", local_data.g

@decorator
def fun2():
    print "fun2 running..."
    time.sleep(2)
    print "local data: ", local_data.g

th1 = threading.Thread(target=fun1)
th2 = threading.Thread(target=fun2)

th1.start()
th2.start()

###輸出####

fun1 running...
fun2 running...
local data: <Thread(Thread-1, started 4828)>
local data: <Thread(Thread-2, started 5812)>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM