Global variables within the thread -ThreadLocal
For each thread gets variable values, use only function by value, but for multi-level functions, parameter passing is too much trouble
ThreadLocal Solutions
import threading local_school = threading.local() def process_student(): # 获取当前线程关联的studnet std = local_school.student # 对当前线程的全局变量拥有修改权 local_school.student = 'my'+local_school.student print("hello, %s (in %s)" % (std, threading.current_thread().name)) def process_stu(): # 对当前线程的全局变量拥有修改权 std = local_school.student print("hello, %s (in %s)" % (std, threading.current_thread().name)) def process_thread(name): # 绑定ThreadLocal的studnet local_school.student = name process_student() process_stu() print(local_school.student) t1 = threading.Thread(target大专栏 线程全局变量ThreadLocaltor">=process_thread, args=('Alce',), name="Thread-A") t2 = threading.Thread(target=process_thread, args=('Bob',), name="Thread-B") t1.start() t2.start() t1.join() t2.join()
Export
hello, Alce (in Thread-A) hello, myAlce (in Thread-A) myAlce hello, Bob (in Thread-B) hello, myBob (in Thread-B) myBob
Analytical
global variable is a local_school ThreadLocal objects, you can write and read each Thread student attributes, but independently of each other. You can local_school as global variables, but each attribute as local_school.student local variables are thread, which could be read without any interference, it does not lock management issues, ThreadLocal internal handles.It can be understood as a global variable local_school is a dict, not only with local_school.student, can also bind to other variables, such as local_school.teacher and so on.
ThreadLocal most common place is binding for each thread a database connection, HTTP request, the user identity information, so that all calls to the handler thread can easily access these resources