When we are writing multi-threaded program, we often encounter two types of variables.
One is a global variable, and multiple threads are shared. In order to avoid the confusion, we have mentioned in the preceding to add lock.
One is a local variable. For one thread only, the threads do not interfere with each other.
For example, task()
a variable defined in a function in the following program count
is a local variable. Even if we create two threads, the increment of the two count
does not affect each other because count
it is task
defined in.
Import Threadingdef Task (): count = 0 for i in range: count + = 1 print countif __name__ = = ' __main__ ': t1 = Threading. Thread (Target=task) t1.start () t2 = Threading. Thread (Target=task) T2.start ()
So, is this a perfect deal? Actually, not yet.
The above example is a very simple example, but when we encounter a more complex business logic, such as multiple local variables, function multiple calls, and so on, so the definition of local variables will become less concise, troublesome.
A function multiple invocation refers to, for example:
We define the function, MethodA (), the method body calls the MethodB (), and the MethodB () method body calls the METHODC () ...
If we call MethodA () in one thread and use a variable attr, then we need to pass attr one layer to the subsequent function.
Is there a way for us to define a variable in the thread so that the function in this one can be called, so it's simple and straightforward?
Python did it for us, that's threadlocal.
The use of Threadlocal only takes three steps:
Here's a look at the code:
# Coding=utf-8import threadinglocal = threading.local () # Create a Global Object Def task (): local.count = 0 # Initializes a thread-in variable, The variable threads do not affect each other. For I in range (+): count_plus () def count_plus (): local.count + = 1 print threading.current_thread ( ). Name, local.countif __name__ = = ' __main__ ': t1 = Threading. Thread (Target=task) t1.start () t2 = Threading. Thread (Target=task) T2.start ()
More Python learning notes-ThreadLocal related articles please follow topic.alibabacloud.com!