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)>

 

posted @ 2016-03-10 21:19  小沙  阅读(2917)  评论(0编辑  收藏  举报