ThreadLocal
In threading
the module, it can be seen that it serves our thread.
Its main function is to store the variables of the current thread. The variable names between threads can be the same, but the variables between threads are isolated, that is, each thread has its own variable copy and does not interfere with each other.
ThreadLocal provides an get()
or set()
to create independently initialized copies of variables.
The working principle of ThreadLocal can be understood as: the ThreadLocal variable is equivalent to a dictionary, the first key of the dictionary is the thread id, and the variable of each thread is stored in its own id dictionary. The structure can be imagined as follows:
local = {
131443: {
# 线程id
"name": "线程1", # 线程变量
"age": 10, # 线程变量
"status": 1 # 线程变量
}
}
See an example below:
import threading
local = threading.local()
def func():
print(f"id:{
local.id},name:{
local.name},num:{
local.num}")
def run(num):
local.id = threading.current_thread().ident
local.name = threading.current_thread().name
local.num = num
func()
if __name__ == "__main__":
t1 = threading.Thread(target=run, args=(1,))
t2 = threading.Thread(target=run, args=(2,))
t1.start()
t2.start()
t1.join()
t2.join()
The execution results are as follows:
id:13022343168,name:Thread-1,num:1
id:13039132672,name:Thread-2,num:2
It can be seen that in the thread, we can directly use the local point to obtain the respective variables, and the variables of each thread are isolated.
So ThreadLocal
what's the use?
- Data isolation between threads
- Perform transaction operations and store thread transaction information
- Database connection, Session session management
- When passing objects across layers, break the constraints between layers
For example, the request context object in Flask is a ThreadLocal
further encapsulation. It can store the request parameters and other variables of each request, and isolate data between request threads.