python学习笔记 - ThreadLocal

咱们在编写多线程程序的时候,每每会遇到两种类型的变量。多线程

  • 一种是全局变量,多个线程共享。为了不改乱为,咱们在前面已经提到说要加锁。函数

  • 一种是局部变量。仅供一个线程使用,线程间相互不影响。线程

例以下列程序中task()函数中定义的count变量就是局部变量。即便咱们建立了两个线程,二者的count递增也不会相互影响,由于count是在task中定义的。code

import threading


def task():
    count = 0
    for i in range(1000):
        count += 1
        print count


if __name__ == '__main__':
    t1 = threading.Thread(target=task)
    t1.start()
    t2 = threading.Thread(target=task)
    t2.start()

那么,这么处理是否是就完美了呢?其实还不是。
以上的例子咱们举的是一个很是简单的例子,可是咱们遇到一个比较复杂的业务逻辑的时候,好比多个局部变量,函数多重调用等,这么定义局部变量就会变得不简洁,麻烦。
函数多重调用是指,例如:
咱们定义了函数,methodA(),这个方法体内调用了methodB(), methodB()方法体中又调用了methodC()...
若是咱们在某一个线程中调用了methodA()而且使用了一个变量attr,那么咱们就须要将attr一层一层地传递给后续的函数。对象

有没有一种方法,能让咱们在线程中定义一个变量后,那么这个线程中的函数就都能调用,如此才叫简洁明了?
Python为咱们作到了,那就是ThreadLocal.
ThreadLocal的用法只须要三步:utf-8

  • 定义一个对象 threading.localget

  • 在线程内给该对象绑定参数。全部绑定的参数都是线程隔离的。thread

  • 在线程内调用。import

下面展现一下代码:变量

# coding=utf-8
import threading

local = threading.local() # 建立一个全局的对象


def task():
    local.count = 0  # 初始化一个线程内变量,该变量线程间互不影响。
    for i in range(1000):
        count_plus()


def count_plus():
    local.count += 1
    print threading.current_thread().name, local.count


if __name__ == '__main__':
    t1 = threading.Thread(target=task)
    t1.start()
    t2 = threading.Thread(target=task)
    t2.start()
相关文章
相关标签/搜索