有个概念叫做线程局部变量,一般我们对多线程中的全局变量都会加锁处理,这种变量是共享变量,每个线程都可以读写变量,为了保持同步我们会做枷锁处理。
但是有些变量初始化以后,我们只想让他们在每个线程中一直存在,相当于一个线程内的共享变量,线程之间又是隔离的,就是局部变量。python threading模块中就提供了这么一个类,叫做local。(推荐学习:python视频教程)
使用局部变量的时候,需要传递参数,比如有这样一个例子,程序需要处理客户申请,每来一个客户,就新开一个线程进行处理,而客户有姓名、年龄、性别等属性(参数),如果都需要传递参数的话很繁琐。python提供了threading.local模块,方便我们实现线程局部变量的传递。直接看下面的例子:
# /usr/bin/env python# coding:utf-8import threading# threading.local对象threadlocalhelper = threading.local()lock = threading.rlock()class mytheadex(threading.thread): def __init__(self, threadname, name, age, sex): super(mytheadex, self).__init__(name=threadname) self.__name = name self.__age = age self.__sex = sex def run(self): global threadlocalhelper threadlocalhelper.threadname = self.name threadlocalhelper.name = self.__name threadlocalhelper.age = self.__age threadlocalhelper.sex = self.__sex mytheadex.threadpoc() # 线程处理函数 @staticmethod def threadpoc(): lock.acquire() try: print 'thread={id}'.format(id=threadlocalhelper.threadname) print 'name={name}'.format(name=threadlocalhelper.name) print 'age={age}'.format(age=threadlocalhelper.age) print 'sex={sex}'.format(sex=threadlocalhelper.sex) print '----------' finally: lock.release()if __name__ == '__main__': tom = {'name': 'tom', 'age': 20, 'sex': 'man'} xiaohua = {'name': 'xiaohua', 'age': 18, 'sex': 'woman'} andy = {'name': 'andy', 'age': 40, 'sex': 'man'} t = (tom, xiaohua, andy) threads = [] for i in range(len(t)): t = mytheadex(threadname='id_{0}'.format(i), name=t[i]['name'], age=t[i]['age'], sex=t[i]['sex']) threads.append(t) for i in range(len(threads)): threads[i].start() for i in range(len(threads)): threads[i].join() print 'all done!!!'
可见,每个线程都可以对threading.local对象进行读写,且互相不干扰。合理使用threading.local可以极大简化代码逻辑,同时保证各个子线程的数据安全。threading.local最大的用处就是http请求时绑定用户的信息,这样每个用户线程可以非常方便访问各自的资源而互不干扰。
更多python相关技术文章,请访问python教程栏目进行学习!
以上就是python怎么定义线程局部变量的详细内容。