What is a thread
In a traditional operating system, each process has an address space, and there is a control thread by default
Thread as the name implies, is a pipeline work process, a pipeline must belong to a workshop, a workshop work process is a process workshop is responsible for the integration of resources together, is a resource unit, and a workshop at least one assembly line
Processes are only used to centralize resources together, and the second process is the executing unit on the CPU
Threads are the process of running code
two why to use threads
1. Under the same process, multiple threads share resources under the process
2. Threads are much smaller than process overhead
Three ways to open threads
#Way One fromThreadingImportThreadImport TimedefSayhi (name): Time.sleep (2) Print('%s Say hello'%name)if __name__=='__main__': T=thread (target=sayhi,args= ('Egon',)) T.start ()Print('Main Thread')Way One
#Mode two fromThreadingImportThreadImport TimeclassSayhi (Thread):def __init__(Self,name): Super ().__init__() Self.name=namedefRun (self): Time.sleep (2) Print('%s Say hello'%self.name)if __name__=='__main__': T= Sayhi ('Egon') T.start ()Print('Main Thread')Mode twoFour other thread-related methods
methods for thread instance objects # isAlive (): Returns whether the thread is active. # getName (): Returns the thread name. # setName (): Sets the thread name. Some of the methods provided by the threading module are:# threading.currentthread (): Returns the current thread variable. # threading.enumerate (): Returns a list that contains the running thread. Running refers to threads that do not include pre-and post-termination threads until after the thread has started and ends. # threading.activecount (): Returns the number of running threads with the same result as Len (Threading.enumerate ()).
fromThreadingImportThreadImportThreading fromMultiprocessingImportProcessImportOSdefWork ():ImportTime Time.sleep (3) Print(Threading.current_thread (). GetName ())if __name__=='__main__': #to open a thread under the main processT=thread (target=Work ) T.start ()Print(Threading.current_thread (). GetName ())Print(Threading.current_thread ())#Main Thread Print(Threading.enumerate ())#along with the main thread, there are two running threads within Print(Threading.active_count ())Print('Main thread /master process') " "Printed results: Mainthread <_mainthread (Mainthread, started 140735268892672) > [<_mainthread (Mainthread, S tarted 140735268892672), <thread (Thread-1, started 123145307557888);] Main thread/main process Thread-1" "View CodeFive Daemon threads
fromThreadingImportThreadImport TimedefSayhi (name): Time.sleep (2) Print('%s Say hello'%name)if __name__=='__main__': T=thread (target=sayhi,args= ('Egon',)) T.setdaemon (True)#must be set before T.start ()T.start ()Print('Main Thread') Print(T.is_alive ())" "Main thread True" "Six-deadlock phenomenon with recursive lock
The so-called deadlock: refers to two or more processes or threads in the course of execution, because of the contention for resources caused by a mutual waiting phenomenon, such as no external force, they will not be able to proceed. The system is said to be in a deadlock state or the system has generated a deadlock.
fromThreadingImportThread,lockImportTimemutexa=Lock () Mutexb=Lock ()classMyThread (Thread):defRun (self): Self.func1 () Self.func2 ( )deffunc1 (self): Mutexa.acquire ()Print('\033[41m%s Get a lock \033[0m'%self.name) Mutexb.acquire ()Print('\033[42m%s get the B lock \033[0m'%self.name) mutexb.release () mutexa.release ()defFunc2 (self): Mutexb.acquire ()Print('\033[43m%s get the B lock \033[0m'%self.name) Time.sleep (2) Mutexa.acquire ()Print('\033[44m%s Get a lock \033[0m'%self.name) mutexa.release () mutexb.release ()if __name__=='__main__': forIinchRange (10): T=MyThread () T.start ( )" "Thread-1 Get a lock Thread-1 get B lock Thread-1 get B lock Thread-2 get a lock then stuck, dead lock" "dead Lock
Workaround, recursive lock, in Python in order to support multiple requests for this same resource in the same thread, Python provides the reentrant lock Rlock.
Seven Semaphore semaphore
Semaphore manages a built-in counter,
Built-in counter whenever acquire () is called-1;
Built-in counter +1 when call Release ();
The counter cannot be less than 0, and when the counter is 0 o'clock, acquire () blocks the thread until another thread calls release ().
Instance (at the same time only 5 threads can get semaphore, which can limit the maximum number of connections to 5)
fromThreadingImportThread, Semaphore#Semaphore Signal VolumeImportTime , Randomsm= Semaphore (5)defTask (name): Sm.acquire ()Print('%s is on the toilet'%name) time.sleep (Random.randint (1, 3) ) sm.release ()#Release Lockif __name__=='__main__': forIinchRange (20): T1= Thread (Target=task, args= ('passer -by%s'%I,)) T1.start ()Signal VolumeEight Event
Same as Process
A key feature of a thread is that each thread is run independently and the state is not measurable. Thread synchronization problems can become tricky if other threads in the program need to determine the state of a thread to decide what to do next. To solve this problem, we need to use the event object in the threading library. The object contains a signal flag that can be set by the thread, allowing the thread to wait for certain events to occur. In the initial state, the signal flag in the event is set to False. A thread if the signal flag of an event object is set to True, he will wake up all the threads waiting for the Eeevent object. If a thread has been set to the real event object, then he will ignore the event and continue executing
event.isset (): Returns the status value of the event, event.wait (): If Event.isset ()= =false will block the thread; Event.set (): Sets the status value of event to True, All blocking pool threads are activated into a ready state, waiting for the operating system to dispatch; Event.clear (): The status value of recovery event is false.
#a thread runs out and immediately notifies the next thread to start running fromThreadingImportThread, EventImporttimeevent=Event ()defLight ():Print('The red light is on.') Time.sleep (3) Event.set ()#green lightdefcar (name):Print('vehicle%s is waiting for green light'%name) event.wait ()#wait for the light to turn green Print('Car%s Pass'%name)if __name__=='__main__': #Traffic LightsT1 = Thread (target=Light ) T1.start ()#Car forIinchRange (10): T= Thread (Target=car, args=(i,)) T.start ()Event
Python concurrent programming Multi-Threading