1. Local thread, ensuring that even multiple threads, their values are isolated from each other. 2. General Object Presentation
Import Threadingimport timeclass A (): passA =A ()def func (num): a.name=num time.sleep (1) Print (A.name,threading.current_thread (). Name)
Results
D:\virtualenv\envs\vuedjango\Scripts\python.exe d:/test/flasktest/flaskpro3/ Local thread. PY4 thread 14 Thread 04 thread 34 thread 24 thread 4Process finished with exit code 0
Because of the need to sleep the last A.name value is the last one, there is no guarantee that each thread corresponds to the value of the corresponding value 3. Local Thread Object Demo
ImportThreadingImport Time#Local Thread ObjectLocal_values =threading.local ()deffunc (num):"""# The first thread comes in, and the local thread object creates a # for him a second thread comes in, and the local thread object creates a unique identity for him {thread 1: {name:1}, thread 2 's unique identity: {name:2},} #注意这里是我自己假设的:p Aram Num:: return:"""Local_values.name=Num#the thread stopped.Time.sleep (2) #Second thread: Local_values.name, go to local_values to get the value of name in value based on its unique identity as key Print(Local_values.name, Threading.current_thread (). Name) forIinchRange (5): Th= Threading. Thread (Target=func, args= (i,), name='Thread%s'%i) Th.start ()
Results
1 Threads 10 Threads 03 threads 32 Threads 24 Threads 4
With a local thread, each time a thread comes in (executing a function), a unique identity is created for the current thread, and the value of the local thread is saved to form a one by one corresponding relationship, and even if the thread waits, it does not all change the value to the last, and the thread execution order is not determined. But its corresponding value must be the value of her unique identity when he executes the function.
Refer to Flask context Source to know that he is to create a unique identity for each thread, here reference her source code to the local thread of the structure of the design and her like
Python Local Thread