然则有些变量初始化今后,我们只想让他们在每一个线程中一向存在,相当于一个线程内的同享变量,线程之间又是断绝的,就是局部变量。python threading模块中就供应了这么一个类,叫做local。(引荐进修:Python视频教程)
运用局部变量的时刻,须要通报参数,比方有如许一个例子,顺序须要处置惩罚客户要求,每来一个客户,就新开一个线程举行处置惩罚,而客户有姓名、岁数、性别等属性(参数),假如都须要通报参数的话很烦琐。Python供应了threading.local模块,轻易我们完成线程局部变量的通报。直接看下面的例子:
# /usr/bin/env python # coding:utf-8 import 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怎样定义线程局部变量的细致内容,更多请关注ki4网别的相干文章!