ThreadLocal understanding in python

ThreadLocalIn threadingthe 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 ThreadLocalwhat's the use?

  1. Data isolation between threads
  2. Perform transaction operations and store thread transaction information
  3. Database connection, Session session management
  4. When passing objects across layers, break the constraints between layers

For example, the request context object in Flask is a ThreadLocalfurther encapsulation. It can store the request parameters and other variables of each request, and isolate data between request threads.

Guess you like

Origin blog.csdn.net/qq_43745578/article/details/129369272