美文网首页
Python多线程变量优化—threadLocal

Python多线程变量优化—threadLocal

作者: 晨畿茨 | 来源:发表于2018-07-30 17:42 被阅读0次

    Python多线程变量优化—threadLocal

    再多线程的环境下,每个线程都有自己的数据。在多线程编程中应该尽量使用局部变量,避免使用全局变量(全局变量需要加锁处理)。使用全局变量时还要考虑变量能不能被共享。

    但是使用局部变量需要在每个函数作为参数传递,很麻烦。

    threadLocal就是用来解决多线程中使用局部变量导致使用繁琐的问题。

    我们实现一个类似对象工厂的线程,上层只需要导入相关参数,即可生成符合要求的对象。

    
    '多线程变量优化,单个线程只是用当前线程的变量'
    '一个ThreadLocal变量虽然是全局变量,但每个线程都只能读写自己线程的独立副本' \
    ',互不干扰。ThreadLocal解决了参数在一个线程中各个函数之间互相传递的问题。'
    __author__ = 'click'
    __date__ = '2018/7/24 下午5:44'
    
    import threading
    # 1.初始化一个threadLocal  
    threadLocal = threading.local()
    
    
    class Student(object):
        def __init__(self, name):
            self.__name = name
    
        def __str__(self):
            return 'Student的属性__name的值是 %s' % (self.__name)
            # 直接使用str会打印出该对象的内存地址,不能打印出上述格式化的内容,必须调用__repr__代替__str__
    
        __repr__ = __str__
    
    
    def addStudent():
        # 取出数据,threadLocal.studentName 很重要!!!
        student = threadLocal.studentName
        print('当前线程是%1s,该线程是用的变量student值是%2s' % (threading.current_thread().name, student.__repr__))
    
    
    def addStudentThread(name):
        # 根据传递的参数,创建相关对象
        # 往threadLocal 中添加数据
        threadLocal.studentName = Student(name)
        addStudent()
    
    
    print('----------使用了threadlocal-------------')
    
    thread1 = threading.Thread(target=addStudentThread, args=('Jack',))
    thread2 = threading.Thread(target=addStudentThread, args=('Tom',))
    
    thread1.start()
    thread2.start()
    thread2.join()
    thread1.join()
    
    运行结果:
    
    ----------使用了threadlocal-------------
    当前线程是Thread-1,该线程是用的变量student值是<bound method Student.__str__ of Student的属性__name的值是 Jack>
    当前线程是Thread-2,该线程是用的变量student值是<bound method Student.__str__ of Student的属性__name的值是 Tom>
    

    使用threadLocal只要分三步:
    前提是导入了threading包

    import threading
    
    • 初始化threadLocal
    threadLocal = threading.local()
    
    • 向threadLocal变量中赋值
    threadLocal.studentName = Student(name)
    
    • 根据变量取出相应的值
    student = threadLocal.studentName
    

    三部完成即可使用threadLocal,由于多线程中每个线程的threadLocal是相互独立的。因此,在多线程的变量优化中,使用threadLocal进行优化是一个很好的选择。


    还有方式可以使用dict进行多线程中变量的优化。能够达到threadLocal相同的功效,只是使用起来比较繁琐。

    Python多线程变量优化(含dict实现代码)

    相关文章

      网友评论

          本文标题:Python多线程变量优化—threadLocal

          本文链接:https://www.haomeiwen.com/subject/esafvftx.html