Multi-threaded concurrency in Python, like other languages, takes into account the problems caused by multi-threaded concurrent access to global variables, and the Python local class solves this problem by letting each thread have a relatively independent local hold of the data, one thread modifying the data, Does not affect data that is saved in other threads.
1 fromThreadingImportThread2 ImportThreading3 Import Time4Local_value=threading.local ()5local_value.x='en'6 classthreadtest (Thread):7 8 def __init__(self,num):9Thread.__init__(self)Tenself.num=Num One A defRun (self): -local_value.x=Self.getname () - forIinchRange (self.num): theTime.sleep (1) - Print(Local_value) - - +ThreadTest (3). Start () -ThreadTest (2). Start ()
The execution results are:
Thread-1Thread-2thread-1thread-2thread-1 in 3.2s]
This shows that although two threads are common to a local_value.x but are really independent of each other variable.
In addition, when
local_value.x=Self.getname () is placed in __init__ (), the run will error, saying ' _thread._local ' object has no attribute ' x ', do not know what the problem, But let's go to dinner first.
Python Thread Local usage