Home >Backend Development >Python Tutorial >python study notes - ThreadLocal

python study notes - ThreadLocal

高洛峰
高洛峰Original
2017-02-16 11:03:011339browse

When we write multi-threaded programs, we often encounter two types of variables.

  • One is a global variable, shared by multiple threads. In order to avoid changing the behavior, we have mentioned before that locking is required.

  • One is local variables. Only used by one thread, and threads do not affect each other.

For example, the count variable defined in the task() function in the following program is a local variable. Even if we create two threads, the increments of both count will not affect each other, because count is defined in task.

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()

So, is it perfect to handle it this way? Not yet.
The above example is a very simple one, but when we encounter a more complex business logic, such as multiple local variables, multiple function calls, etc., defining local variables in this way will become unsuccinct. ,trouble.
Multiple calls of functions refer to, for example:
We have defined a function, methodA(), this method body calls methodB(), methodB() method body calls methodC()...
If we call methodA() in a thread and use a variable attr, then we need to pass attr to subsequent functions layer by layer.

Is there a way that allows us to define a variable in a thread, and then all functions in the thread can be called? This is simple and clear?
Python does it for us, that is ThreadLocal.
The usage of ThreadLocal only requires three steps:

  • Define an object threading.local

  • Bind parameters to the object within the thread. All bound parameters are thread-isolated.

  • Call within the thread.

The code is shown below:

# 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()

For more python study notes - ThreadLocal related articles, please pay attention to the PHP Chinese website!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn