It is better for a thread to use its own local variables than to use global variables.
Local variables can only be seen by the thread themselves and will not affect other threads
Changes to global variables must be locked
ThreadLocal Thread Local Variables
Import threading
# Create a global threadlocal object:
Local_school = Threading.local ()
Def process_student ():
# Gets the student associated with the current thread:
std = local_school.student
Print (' Hello,%s (in%s) '% (Std, Threading.current_thread (). Name))
def process_thread (name):
# bind Threadlocal's student:
Local_school.student = Name
Process_student ()
T1 = Threading. Thread (target= process_thread, args= (' Alice ',), name= ' thread-a ')
T2 = Threading. Thread (target= process_thread, args= (' Bob ',), name= ' Thread-b ')
T1.start ()
T2.start ()
T1.join ()
T2.join ()
Execution Result:
Hello, Alice (in thread-a)
Hello, Bob (in Thread-b)
The global variable Local_school is a Threadlocal object,
Each thread can read and write student properties to it, but it does not affect each other.
You can think of Local_school as a global variable,
But each attribute, such as local_school.student, is a thread's local variable that can be read and written without interfering
Can be understood as a global variable local_school is a dict, not only can use Local_school.student, can also bind other variables, such as local_school.teacher, etc.
Threadlocal solves the problem of passing arguments between functions in a thread.
Local variables in the python thread threadlocal