ImportThreading#To create a global threadlocal object:Local_school =threading.local ()defprocess_student ():#gets the student associated with the current thread:std =local_school.studentPrint('Hello,%s (in%s)'%(Std, Threading.current_thread (). Name))defProcess_thread (name):#binding the threadlocal student:Local_school.student =name Process_student () T1= Threading. Thread (Target=process_thread, args= ('Douzi',), name='thread-a') T2= Threading. Thread (Target=process_thread, args= ('Douzi2',), name='Thread-b') T1.start () T2.start () T1.join () T2.join ()
Hello, Douzi (in thread-a) Hello, Douzi2 (in Thread-b)
A global variable local_school
is an ThreadLocal
object , each Thread
of which can read student
and write properties, but does not affect each other. You can think of it local_school
as a global variable, but each property, such as local_school.student
a thread's local variable, can read and write without interfering with each other, and does not have to manage the lock problem, which is ThreadLocal
handled internally.
Can be understood as a global variable local_school
is one dict
, not only can be used local_school.student
, you can also bind other variables, such as local_school.teacher
and so on.
ThreadLocal
The most common place is to bind a database connection for each thread, HTTP requests, user identity information , and so on, so that all the calls to the processing functions of a thread can be easily accessed by these resources .
Python Learning Notes (29) ThreadLocal