python怎么定义线程局部变量-Python教程

资源魔 34 0
有个概念叫做线程部分变量,普通咱们对多线程中的全局变量城市加锁解决,这类变量是同享变量,每一个线程均可以读写变量,为了放弃同步咱们会做桎梏解决。

然而有些变量初始化当前,咱们只想让他们正在每一个线程中不断存正在,相称于一个线程内的同享变量,线程之间又是隔离的,就是部分变量。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怎样界说线程部分变量的具体内容,更多请存眷资源魔其它相干文章!

标签: Python python教程 python编程 python使用问题

抱歉,评论功能暂时关闭!