Threads together as a function of a thread
ImportThreadingImport Timedefrun (n):Print("Task", N) time.sleep (2) Print("Task Done", N) start_time=time.time () T_objs= []#Save Thread Instance forIinchRange (10): T= Threading. Thread (Target=run, args= ("t-%s"% i,))#up ThreadT.start () t_objs.append (t)#in order not to block the boot of the subsequent thread, do not join here, first put in a list forTinchT_OBJS:#loop Thread instance list, waiting for all threads to finish executingT.join ()Print("----------All threads have finished ...")Print("Cost :", Time.time ()-start_time)
The test time is slightly greater than 2 seconds. The main thread and this main thread start the sub-thread is parallel, the main thread of execution and child thread-independent, in order to let the main thread in the program to wait for the execution of the child thread, only add the Join () method.
Two-way thread from a class
ImportThreadingImport TimeclassMyThread (Threading. Thread):def __init__(self, N, sleep_time): Super (MyThread, self).__init__() SELF.N=N self.sleep_time=Sleep_timedefRun (self):#overrides the run function of the parent class, so it can only be the name of the function Print("runnint Task", SELF.N) time.sleep (self.sleep_time)Print("task Done,", SELF.N) T1= MyThread ("T1", 2) T2= MyThread ("T2", 4) T1.start () T2.start () T1.join () T2.join ()#after writing these two sentences, execute print ("main thread ...") before executing the T1 and T2 before executing print ("Main thread ...").
Two daemon threads
ImportThreadingImport Timedefrun (n):Print("Task", N) time.sleep (5) Print("Task Done", N,threading.current_thread ()) Start_time=time.time () T_objs= []#Save Thread Instance forIinchRange (5): T= Threading. Thread (target=run,args= ("t-%s"%I,)) T.setdaemon (True)#set the current thread as the daemon threadT.start () t_objs.append (t)#in order not to block the boot of the subsequent thread, do not join here, first put in a list forTinchT_OBJS:#loops The thread instance list, waits for all threads to finish, and the program does not go down until the thread is executed.T.join () time.sleep (1)Print("----------All threads have finished ...", Threading.current_thread (), Threading.active_count ())Print("Cost :", Time.time ()-start_time)
If the daemon thread is not set,
As you can see, after the print statement is executed, the program waits for all the child threads to execute.
Plus the result after the daemon thread
The program does not wait for the child thread to finish executing and then exits.
Add join () After the result of (that is, the comments of the two lines of code are canceled):
This is mostly compared to the order in which they are executed.
Three-wire lock
ImportThreadingImport Timedefrun (N): Lock.acquire ()#Lock, GlobalNum Num+ = 1Time.sleep (0.2) lock.release ()#UnlockLock= Threading. Lock ()#generate a thread lock instancenum =0t_objs= []#Save Thread Instance forIinchRange (5): T= Threading. Thread (Target=run, args= ("t-%s"%I,)) T.start () t_objs.append (t)#in order not to block the boot of the subsequent thread, do not join here, first put in a list forTinchT_OBJS:#loop Thread instance list, waiting for all threads to finish executingT.join ()Print("All threads have finished:", Threading.current_thread (), Threading.active_count ())Print("Num:", num)
After locking, in the middle part of the lock program is serial, Python3 automatic lock, so you can no longer lock,
Four recursive locks
Importthreading, timedefrun1 ():Print("grab The first part data") Lock.acquire ()GlobalNum Num+ = 1lock.release ()returnNumdefrun2 ():Print("grab the second part data") Lock.acquire ()Globalnum2 num2+ = 1lock.release ()returnnum2defrun3 (): Lock.acquire () Res= Run1 ()#The run1 is executed here, and the lock is already in the run1, so a recursive lock is required, just like a normal lock, only declared as a recursive lock on the line. Print('--------between RUN1 and run2-----') Res2=run2 () lock.release ( )Print(res, res2) num, num2=0, 0lock= Threading. Rlock ()#declared as recursive lock forIinchRange (1): T= Threading. Thread (target=run3) T.start () whileThreading.active_count ()! = 1: Print(Threading.active_count ())Else: Print('----All threads done---') Print(Num, num2)
The recursive lock and the thread lock usage are the same, except that they need to be declared as recursive locks at the time of declaration.
Five signal volumes
Importthreading, timedefrun (N): Semaphore.acquire () time.sleep (1) Print("Run the thread:%s\n"%N) semaphore.release ()if __name__=='__main__': Semaphore= Threading. Boundedsemaphore (5)#allow up to 5 threads to run at a time forIinchRange (22): T= Threading. Thread (Target=run, args=(i,)) T.start () whileThreading.active_count ()! = 1: Pass #print Threading.active_count ()Else: Print('----All threads done---') #print (num) #The information number is the same as the thread lock usage, just declaring an information number on the declaration.
The information number is the same as the thread lock usage, except that a semaphore is declared at the time of the Declaration.
Six Events Event
Import TimeImportthreadingevent=Threading. Event ()defLighter (): Count=0 event.set ()#set the green light first whileTrue:ifCount >5 andCount < 10:#change to a red lightEvent.clear ()#clear the sign. Print("\033[41;1mred Light is on....\033[0m") elifCount >10: Event.set ()#Turn GreenCount =0Else: Print("\033[42;1mgreen Light is on....\033[0m") Time.sleep (1) Count+=1defcar (name): whileTrue:ifEvent.is_set ():#represents the green light Print("[%s] running ..."%name) Time.sleep (1) Else: Print("[%s] sees red light, waiting ...."%name) event.wait ()Print("\033[34;1m[%s] green light was on, start going...\033[0m"%name) Light= Threading. Thread (target=lighter,) light.start () car1= Threading. Thread (target=car,args= ("Tesla",)) Car1.start ()
The event program has only three states, set (), wait (), clear (), can do things separately in these three states,
Seven Thread queue
#Producer Consumer ModelImportThreading,timeImportQueueq= Queue. Queue (maxsize=10)#define a common thread queuedefProducer (name): Count= 1 whileTrue:q.put ("Bun%s"%count)Print("production of steamed buns", Count) Count+=1Time.sleep (0.5)defConsumer (name):#While q.qsize () >0: whileTrue:Print("[%s] fetch [%s] and eat it ..."%(name, Q.get ())) Time.sleep (1) P= Threading. Thread (target=producer,args= ("Zhangsan",)) C= Threading. Thread (target=consumer,args= ("Lishi",)) C1= Threading. Thread (target=consumer,args= ("Wangwu",)) P.start () C.start () C1.start ( )
Multithreading Learning Summary