Python: Thread Advanced

Source: Internet
Author: User

1, daemon thread

Import Time fromThreadingImportThreaddeffunc ():Print('start executing a child thread') Time.sleep (3)    Print('Child thread Execution complete') T= Thread (target=func) T.setdaemon (True)#The Process settings daemon is a property daemon = TrueT.start () T2= Thread (target=func) T2.start () T2.join ()#waiting for T2 to end
# The daemon daemon is waiting for the main process or the code in the main thread to finish executing
# t2 = Thread (Target=func)
# T2.start () ---> Code execution complete
# The daemon thread is over.
# The main thread is not over wait T2 continue execution
# t2 execution Complete main thread end

# t2 = Thread (Target=func)
# T2.start ()
# T2.join () # Wait for T2 to finish executing this line of code before execution is complete
# t2 Thread Execution Complete
# No code in main thread, end of daemon thread

2, lock

Import Time fromThreadingImportThread fromThreadingImportLockdeffunc ():GlobalN Time.sleep (2) lock.acquire () Temp= N#get n from the processTime.sleep (0.01) n= Temp-1#get results, then store back to processlock.release () n= 100Lock=Lock () t_lst= [] forIinchRange (100): T= Thread (target=func) T.start () t_lst.append (t) [T.join () forTinchT_lst]Print(n)#GIL is not lock data but lock thread#Special cases in multi-threading are still locked to the data

3, deadlock

Import Time fromThreadingImportRlock fromThreadingImportThreadm= KZ = Rlock ()#defEat (name): Kz.acquire ()#get the keys .    Print('%s got the chopsticks.'%name) M.acquire ()Print('%s got a face.'%name)Print('%s eating Noodles'%name) m.release () kz.release ()defEAT2 (name): M.acquire ()#no key .    Print('%s got a face.'%name) Time.sleep (1) Kz.acquire ()Print('%s got the chopsticks.'%name)Print('%s eating Noodles'%name) kz.release () m.release ()
There is a deadlock in the different threads that are just going to operate on the two data.
4, Signal volume
1 Import Time2 ImportRandom3  fromThreadingImportThread4  fromThreadingImportSemaphore5 deffunc (N,sem):6 Sem.acquire ()7     Print('thread-%s Start'%N)8 Time.sleep (Random.random ())9     Print('thread-%s done'%N)Ten sem.release () OneSEM = Semaphore (5)#a lock with 5 keys . A  forIinchRange (20): -Thread (target=func,args=(I,sem)). Start () - #What is the difference between the semaphore and the thread pool?  the #The same point, after the semaphore acquire, is executed at the same time as the thread pool with only n - #different points -     #the number of threads in the thread pool is a total of 5 thread semaphores. There are several tasks to open several threads - #can you execute many threads at the same time for a semaphore-constrained program?  + #In fact, the semaphore does not affect the concurrency of the thread or process, only the traffic limit during the lock-in phase

5, Event

Import TimeImportRandom fromThreadingImportEvent fromThreadingImportThreaddefConn_mysql ():#connecting to a databaseCount = 1 while  notE.is_set ():#executes the statement within the loop when the flag of the event is False        ifCount>3:            RaiseTimeouterrorPrint('attempt to connect%s times'%count) Count+ = 1e.wait (0.5)#has been blocked to become only blocking 0.5    Print('Connection Successful')#receive the set instruction within the Check_conn function to let flag become true jump out of the while loop, execute this sentence codedefcheck_conn ():" "detects if the database server is connected properly" "Time.sleep (Random.randint ())#time to simulate connection detectionE.set ()#the flag that tells the event that the database can connecte=Event () Check= Thread (target=check_conn) Check.start () Conn= Thread (target=conn_mysql) Conn.start ()

6, conditions

ImportThreadingdefrun (N): Con.acquire () con.wait ()#wait.    Print("run the thread:%s"%N) con.release ()if __name__=='__main__': Con= Threading. Condition ()#condition = function of lock + wait     forIinchRange (10): T= Threading. Thread (Target=run, args=(i,)) T.start () whileTRUE:INP= Input ('>>>')        ifINP = ='Q':             BreakCon.acquire ()#the lock in the condition is a recursive lock        ifINP = =' All': Con.notify_all ()Else: con.notify (int (INP))#Transmit signal Notify (1)-can release a threadCon.release ()

7, Timer

 from Import Timer def Hello ():         Print ("Hello,world")  while True:    #  every once in a while to open a thread    t = timer (ten, Hello)   #  timed to open a thread, perform a task                       #  timing: How long after the unit is S                      #  the task to perform: function name    t.start ()

8, queue

ImportQUEUEPQ= Queue. Priorityqueue ()#The smaller the value, the higher the value, the lower the ASC code, the first outPq.put (1,'Z')) Pq.put (1,'b')) Pq.put (15,'C')) Pq.put (2,'D'))#Print(Pq.get ())Print(Pq.get ())

9,concurrent with thread pools and callback functions

Import TimeImportRandom fromConcurrentImportFuturesdeffuncname (n):Print(n) time.sleep (Random.randint (1,3))    returnN'*'defCall (args):Print(Args.result ()) Thread_pool= Futures. Threadpoolexecutor (5)#thread PoolThread_pool.map (Funcname,range (10))#map, which is inherently asynchronous, receives data from an iterative object and does not support return valuesF_lst = [] forIinchRange (10): F= Thread_pool.submit (funcname,i)#submit incorporates the ability to create thread objects and startf_lst.append (f) thread_pool.shutdown ()#Close () join () forFinchF_lst:#must be in the order of the results    Print(F.result ())#F.result () block, etc. f execution results obtained#callback function Add_done_callback (name of callback function)Thread_pool.submit (funcname,1). Add_done_callback (Call)



Python: Thread Advanced

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.