When writing multi-threaded programs, we often encounter two types of variables. One is global variables, which are shared by multiple threads. In order to avoid chaos, we have mentioned that the lock should be applied. One is local variables. It is only used by one thread and does not affect each other. For example, in the following program, we often encounter two types of variables when writing multi-threaded programs.
-
One is global variables, which are shared by multiple threads. In order to avoid chaos, we have mentioned that the lock should be applied.
-
One is local variables. It is only used by one thread and does not affect each other.
For exampletask()ThecountA variable is a local variable. Even if we create two threadscountThe increment does not affect each other, becausecountYestask.
import threadingdef task(): count = 0 for i in range(1000): count += 1 print countif __name__ == '__main__': t1 = threading.Thread(target=task) t1.start() t2 = threading.Thread(target=task) t2.start()
So, is this perfect? Not yet.
The above example is a very simple example, but when we encounter a complicated business logic, such as multiple local variables and multiple function calls, therefore, defining local variables is not concise and troublesome.
Multiple function calls refer to, for example:
We have defined a function, methodA (). The method body calls methodB (), and methodB () method body calls methodC ()...
If we call methodA () in a thread and use the attr variable, we need to pass the attr layer by layer to subsequent functions.
Is there a way for us to define a variable in the thread so that all functions in this thread can be called, so it is concise and clear?
Python has done it for us, that is, ThreadLocal.
The usage of ThreadLocal only takes three steps:
-
Define an object threading. local
-
Bind parameters to the object within the thread. All bound parameters are thread-isolated.
-
Called within the thread.
The following code is displayed:
# Coding = utf-8import threadinglocal = threading. local () # create a global object def task (): local. count = 0 # initialize a variable in the thread, which does not affect each other. For I in range (1000): 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 ()
For more python study Notes-ThreadLocal articles, refer to PHP Chinese network!