標准庫的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)>
