Network Programming Basics-Multi-threaded---concurrent.futures module---event---semaphore semaphore---timer timer---deadlock phenomenon recursive lock----thread queues queue

Source: Internet
Author: User
Tags semaphore

1 concurrent.futures module:

#From ABC import Abstractmethod,abcmeta##class A (Metaclass=abcmeta):#def mai (self):#Pass#@classmethod#class B (A):#def mai (self):#Pass#Abstract class----defines some interface standards for subclasses @abstractmethod=================== process pool and thread pool ===================the concept of introducing pools is to control the number of Concurrent.futures =======>>> asynchronous calls # 1 ====== shutdown (wait=true) ====>> close () +joi N () shutdown (wait=false) =======>> Close () # 2 ====== submit ===>> Apply_async () # 3 ====== map=====# 4 = = ==add_done_callback (FN) fromConcurrent.futuresImportThreadpoolexecutor,processpoolexecutorImportTime,random,os=============================== Compute multiple process pools ==================================================#def work (n):#print ('%s is running '%os.getpid ())#Time.sleep (Random.randint (1,3))#return n*n## 1#if __name__ = = ' __main__ ':#Executor_p=processpoolexecutor (4)#futures=[]#For I in Range (Ten):#Future=executor_p.submit (work,i) # Gets the result of the asynchronous commit's future object#futures.append (future)#Executor_p.shutdown (wait=true) # executor_p = Shutdown#print (' main ')#For obj in futures:#print (Obj.result ()) # results### 2 ===== with AS#if __name__ = = ' __main__ ':#With Processpoolexecutor (4) as E:#futures=[]#For I in range (6):#future=e.submit (work,i)#futures.append (future)#print (' Main ')#For obj in futures:#print (Obj.result ())#================================ shorthand ===========================================# from Concurrent.futures import threadpoolexecutor# from threading import current_thread,enumerate,active_count## def work (n): # print ('%s is running '%current_thread ()) # return n**2## if __name__ = = ' __main__ ': # with THREADPO Olexecutor () as executor:# Futures=[executor.submit (work,i) for I in range (+)]## for I in futures:# P Rint (I.result ())=======================================  io multiple thread pool ===========================##def work (n):#print ('%s is running '%os.getpid ())#Time.sleep (Random.randint (1,3))#return n*n## 1#if __name__ = = ' __main__ ':#Executor_p=threadpoolexecutor (+)#futures=[]#For I in Range (Ten):#Future=executor_p.submit (work,i) # Gets the result of the asynchronous commit's future object#futures.append (future)#Executor_p.shutdown (wait=true) # executor_p = Shutdown#print (' main ')#For obj in futures:#print (Obj.result ()) # results### 2 ===== with AS#if __name__ = = ' __main__ ':#With Threadpoolexecutor (+) as E:#futures=[]#For I in range (6):#future=e.submit (work,i)#futures.append (future)#print (' Main ')#For obj in futures:#print (Obj.result ())===========================  map ======== Loop submits multiple results ================================= ===
#From concurrent.futures import threadpoolexecutor#From threading Import Current_thread,enumerate,active_count##def work (n):#print ('%s is running '%current_thread ())#return n**2##if __name__ = = ' __main__ ':#With Threadpoolexecutor () as executor:#Futures=[executor.map (Work,range (+))]#[1,2,3,4,5]#Executor.map (Work,range (6)) passes the back iteration object as a parameter to the work#===============================future.add_done_callback (FN)======== callback function ========================== ===================##From concurrent.futures import processpoolexecutor##def work (n):#return n**n##def WORK2 (m):#M=m.result ()#print (M/2)##if __name__ = = ' __main__ ':#With Processpoolexecutor () as E:#For I in range (6):#E.submit (work,i). Add_done_callback (WORK2)#======================future.exeption (4) ======== wait Time-wait Timeout exception =============================================

2. Event:

collaborative work between two processes fromThreadingImportEvent,current_thread,threadImportTime 
e =Event () defcheck ():Print('%s is detecting'%Current_thread (). GetName ()) Time.sleep (3) e.set () # confirm Settings defConn (): Count=1 while notE.is_set ():ifCount >3: RaiseTimeouterror ('Connection timed out') Print('%s is waiting for connection'%Current_thread (). GetName ()) e.wait (Timeout =0.1) # time-out limit number of attempts Count+=1Print('%s is connecting'%Current_thread (). GetName ())if __name__=='__main__': T1=thread (target=check) T2=thread (target=conn) T3=thread (target=conn) T4=thread (target=conn) T1.start () T2.start () T3.start () T4.start ()

3. Signal Volume semaphore:

 from Import Semaphore  semaphore Semaphore---Essence is a lock ====== control the number of simultaneous processes (more processes can be opened in the background) process Pool  ----number of processes running concurrently () 

4.-Timers Timer:

# From threading Import Timer ## def hello (): #      print (' Hello ')##  t=timer (4,hello)  # timer--is a subclass of thread  4 seconds after start #  T.start ()

5. Deadlock Phenomenon Recursive Lock:

============================== deadlock Phenomenon ================================= recursive lock rlock---can be aquire multiple timesOne count per aquire plus one, as long as the count is not one can not be grabbed by other threads Mutex ----can only be aquire once fromThreadingImportThread,lock,current_threadImportTimemutexa=Lock () Mutexb=Lock ()classMythread (Thread):defRun (self): Self.f1 () self.f2 ( )defF1 (self): with Mutexa:Print('%s grabbed a.'%Current_thread (). GetName ()) with Mutexb:Print('got a B.'%Current_thread (). GetName ())defF2 (self): with Mutexb:Print('got a B.'%Current_thread (). GetName ()) Time.sleep (0.1) with Mutexa:Print('grab A.'%Current_thread (). GetName ())if __name__=='__main__':     forIinchRange (6): T=Mythread () T.start ( )

6. Thread Queuing queue:

ImportQueueq=queue. Queue (4) Q.put (2) Q.put (2) Q.put (2) Q.put (2)Print(Q.get ())Print(Q.get ())Print(Q.get ())Print(Q.get ()) #  1 priority queue Q=queue. Priorityqueue (3) Q.put (10,'TSD')) Q.put (4,'ard'))#The same precedence compares the subsequent dataQ.put (10,'ASD'))#The smaller the number, the higher the priority .Print(Q.get ())Print(Q.get ())Print(Q.get ()) #  2 advanced post-out---stack queue Q=queue. Lifoqueue (3)

Network Programming Basics-Multi-threaded---concurrent.futures module---event---semaphore semaphore---timer timer---deadlock phenomenon recursive lock----thread queues queue

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.