Python 51st days ---- thread, Event, queue, python 51st days

Source: Internet
Author: User

Python 51st days ---- thread, Event, queue, python 51st days

Differences between processes and threads:

Thread = instruction set, process = resource set (thread set)

1. threads in the same process share the memory space. The process and process are independent.

2. threads in the same process can communicate directly. inter-process communication must be implemented through an intermediate proxy.

3. The creation thread is simple. The process is a clone parent process.

4. One thread can control and operate other threads in the same process, but the process can only operate sub-processes.

5. Fast thread startup and slow process startup

Thread example:

1 import time, threading 2 3 def run (attr): 4 print ('output: ', attr) 5 time. sleep (3) 6 7 8 t1 = threading. thread (target = run, args = ('first thread',) 9 t2 = threading. thread (target = run, args = ('second thread',) 10 11 t1.start () # Start Thread 112 t2.start () # Start Thread 2
1 def run2 (attr): 2 print ('output: ', attr) 3 time. sleep (3) 4 5 run2 ('first thread') 6 run2 ('second thread') 7 # convert the above into series execution

 

Inherited thread-class write thread

1 #! Usr/bin/env python 2 #-*-coding: UTF-8-*-3 # Author calmyan 4 5 import threading, time 6 7 class thre (threading. thread): # inherit the Class 8 def _ init _ (self, n, times) in the Thread: 9 super (thre, self ). _ init _ () 10 self. n = n11 self. teims = times12 def run (self): 13 print ('execution first thread: ', self. n) 14 time. sleep (self. teims) 15 16 star_time = time. time () 17 t1 = thre ('first thread', 3) 18 t2 = thre ('second thread', 4) 19 t1.start () 20 t2.start () 21 t1.join () # join wait for the thread to finish executing 22 23 t2.join () 24 den_time = time. time ()-star_time25 print (den_time)

 

 

Wait until the thread execution is complete and use. join

1 import time, threading 2 lock = threading. lock () # define a thread lock variable 3 def run (attr): 4 Lock. acquire () # apply for a thread lock 5 global num 6 print ('output: ', attr) 7 # time. sleep (3) 8 num + = 1 9 lock. release () # release thread lock 10 time. sleep (3) 11 print ('output finished '. center (10, 'two') 12 star_time = time. time () # Start time 13 14 num = 015 re_lilst = [] # define a list 16 for I in range (50): 17 t1 = threading. thread (target = run, args = ('% s Thread' % I),) # create Thread 18 # t1.setDaemon (True) # Set as Daemon. When the main thread is completed, the daemon also stops 19 t1.start () # Start thread 20 re_lilst.append (t1) # Do not use JOIN to avoid blocking as serial 21 22 print (threading. current_thread (), threading. active_count () # view the main sub-active thread of the thread 23 # print ('sub-thread '. center (40, '☆') 24 print ('digit: ', num) 25 for I in re_lilst: # Wait for the thread to finish 26 I. join () 27 print ('Number: ', num) 28 print ('main thread '. center (60, '◇ '), threading. current_thread (), threading. active_count () 29 30 den_time = time. time ()-star_time # Total time 31 print (den_time)
View Code

The daemon process is equivalent to a subordinate of the main process. When the main process ends, it will stop no matter whether the execution in the daemon process is complete or not!

1 import time, threading 2 lock = threading. lock () # define a thread lock variable 3 def run (attr): 4 Lock. acquire () # apply for a thread lock 5 global num 6 print ('output: ', attr) 7 8 # time. sleep (3) 9 num ++ = 110 lock. release () # release the thread lock 11 time. sleep (3) 12 print ('output finished '. center (10, 'two') 13 14 star_time = time. time () # Start time 15 16 num = 017 re_lilst = [] # define a list 18 for I in range (50): 19 t1 = threading. thread (target = run, args = ('% s Thread' % I),) # create Thread 20 t1.setDaemon (True) # set as daemon when the main Thread is completed, the daemon also stops 21 t1.start () # Starts thread 22 re_lilst.append (t1) # does not need to JOIN to avoid blocking as serial 23 24 print (threading. current_thread (), threading. active_count () # view the main sub-active thread of the thread 25 # print ('sub-thread '. center (40, '☆') 26 print ('digit: ', num) 27 # for I in re_lilst: # Wait for the thread to finish 28 # I. join () 29 print ('Number: ', num) 30 print ('main thread '. center (60, '◇ '), threading. current_thread (), threading. active_count () 31 32 den_time = time. time ()-star_time # Total time 33 print (den_time)
View Code

Thread lock, which is not used in py3:

Lock = threading. Lock ()

Lock. acquire ()

Recursive lock for Recursive threads

1 import time, threading 2 3 def run (I): 4 print ('output: ------- ', I) 5 lock. acquire () # apply for lock 6 global num1 7 num1 + = 1 8 time. sleep (0.1) 9 lock. release () # release lock 10 return num111 12 def run2 (I): 13 lock. acquire () # apply for Lock 14 global num215 print ('output: 22', I) 16 num2 + = 117 time. sleep (0.1) 18 lock. release () # release lock 19 return num220 21 def run3 (I): 22 lock. acquire () # apply for Lock 23 res = run (I) 24 print ('output: 333 ', I) 25 res2 = run2 (I) 26 time. sleep (0.1) 27 print (res, res2) 28 lock. release () # release lock 29 30 31 if _ name _ = '_ main _': 32 star_time = time. time () # Start time \ 33 num1, num2 = 0,034 # lock = threading. lock () # defines a thread lock. If it is a thread Lock, an error occurs in recursion. 35 lock = threading. RLock () # define a recursive lock 36 37 for I in range (10): 38 # t1 = threading. thread (target = run, args = ('% s Thread' % I),) # create Thread 39 t1 = threading. thread (target = run3, args = ('% s Thread' % I),) # create Thread 40 t1.start () # Start Thread 41 42 else: 43 print ('number of active threads: ', threadin G. active_count () # view the number of active threads in the thread 44 45 46 while threading. active_count ()! = 1: # there is not only one thread, that is, determine whether there is the remaining main thread 47 # print (threading. active_count () # view the number of active threads 48 pass49 else: 50 print ('main thread: pid, number of active Threads '. center (60, '◇ '), threading. current_thread (), threading. active_count () #51 den_time = time. time ()-star_time # Total time 52 print (den_time) 53 print (num1, num2)
View Code

Semaphores are equivalent to multiple thread locks.

1 #! Usr/bin/env python 2 #-*-coding: UTF-8-*-3 # Author calmyan 4 5 #! Usr/bin/env python 6 #-*-coding: UTF-8-*-7 # Author calmyan 8 import time, threading 9 10 def run (attr): 11 semaphore. acquire () # apply for a semaphore thread lock 12 global num13 print ('output: ', attr) 14 time. sleep (1) 15 semaphore. release () # release the semaphore thread lock 16 17 star_time = time. time () # Start time 18 if _ name _ = '_ main _': 19 20 semaphore = threading. boundedSemaphore (4) # semaphore allows a maximum of several threads to run simultaneously (multiple locks) 21 for I in range (50): 22 t1 = threading. thread (target = run, ar Gs = ('% s thread' % I),) # create thread 23 t1.start () # Start thread 24 25 while threading. active_count ()! = 1: # there is not only one thread, that is, determine whether there is the remaining main thread 26 pass27 else: 28 print ('main thread '. center (60, '◇ '), threading. current_thread (), threading. active_count () 29 den_time = time. time ()-star_time # Total time 30 print (den_time)
View Code

Event thread flag

Traffic Light example

1 #! Usr/bin/env python 2 #-*-coding: UTF-8-*-3 # Author calmyan 4 5 import threading, time 6 7 event = threading. event () # generate an identifier object 8 def lighter (): #9 count = 0 # define time SECONDS 10 event. set () # set flag 11 while True: 12 if count> 9 and count <15: # set to red light 13 event. clear () # clear the flag, 14 print ('\ 033 [41; 1 m turns to a red light! \ 033 [0m') 15 elif count> = 15 and count <18: # For yellow light 16 17 print ('\ 033 [43; 1 m to yellow light! \ 033 [0m') 18 elif count> = event. set () # set flag 20 print ('\ 033 [42; 1 m to green! \ 033 [0m') 21 count = 0 # re-timing 22 else: 23 print ('\ 033 [42; 1 m green .....! \ 033 [0m') 24 time. sleep (1) 25 count + = 1 # Add 26 27 28 def car (name): 29 while True: 30 if event every second. is_set (): # if there is a sign, it indicates that the green light 31 print ('[% s] is driving .... '% name) 32 time. sleep (1) 33 else: 34 print ('[% s] waiting ..... '% name) 35 event. wait () # wait for the 36 print sign to be obtained ('green light, [% s] continue driving... '% name) 37 time. sleep (1) 38 39 40 light = threading. thread (target = lighter,) # define a Thread 41 light. start () # start thread 42 43 car1 = threading. thread (target = car, args = ('hongqi marker',) # generate a car Thread 44 car1.start ()
View Code

 

Queue producer consumer model

 

1 #! Usr/bin/env python 2 #-*-coding: UTF-8-*-3 # Author calmyan 4 5 # queue producer consumer model 6 7 import threading, time, queue 8 9 q = queue. queue () # create a Queue 10 11 def produ (name): # Production Function 12 count = 013 while True: 14 bz = name + str (count) 15 q. put (bz) 16 print ('[% s] produced, number of [% s] g steamed stuffed bun' % (name, count, bz )) 17 count ++ = 118 time. sleep (1.5) 19 20 def consump (name): # consumer 21 while True: 22 I = q. get () # get 23 print ('[% s] get steamed stuffed bun [% s], and eat' % (name, I) 24 time. sleep (0.5) 25 26 27 p1 = threading. thread (target = produ, args = ('wang Wu Bao sub-Shop ',) # create a new Thread producer 28 p2 = threading. thread (target = produ, args = ('mahjong six package pload',) # create a new Thread producer 29 r1 = threading. thread (target = consump, args = ('zhang san',) # create a new Thread consumer 30 r2 = threading. thread (target = consump, args = ('lily',) # create a new Thread consumer 31 p1.start () 32 p2.start () 33 r1.start () 34 r2.start ()
View Code

 

Related Article

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.