The difference between a process and a thread:
thread = = Instruction set, Process = = Resource Set (thread set)
1. Threads in the same process share memory space, process is independent from process
2, the thread in the same process can communicate directly, the process and communication must pass through an intermediary agent to achieve
3, create the thread simple, create the process, is the clone parent process
4. A thread can control and manipulate other threads in the same process, but the process can only manipulate child processes
5, Thread startup speed is fast, process startup speed is relatively slow
Threading 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 ',)) T1.start () #启动线程112 T2.start () #启动线程2
1 def run2 (attr): 2 print (' Output: ', attr) 3 time.sleep (3) 4 5 run2 (' first thread ') 6 run2 (' Second thread ') 7 #以上转为串联执行
Inheriting thread class write threads
1 #! Usr/bin/env Python 2 #-*-coding:utf-8-*-3 # Author Calmyan 4 5 import threading,time 6 7 class thre (threading. Thread): #继承线程中的类 8 def __init__ (self,n,times): 9 Super (thre,self). __init__ () self.n=n11 SELF.TEIMS=TIMES12 def run (self): print (' execution line: ', SELF.N) time.sleep (self.teims) star_time= Time.time () T1=thre (' The Frontline ', 3) t2=thre (' Second thread ', 4) T1.start () T2.start () t1.join () #join等待该线程执行完成22 T2.join ( ) den_time=time.time ()-star_time25 print (den_time)
Wait for thread execution to complete, with. Join
1 Import time, threading 2 lock=threading. Lock () #定义一个线程锁变量 3 def Run (attr): 4 lock.acquire () #申请一个线程锁 5 global num 6 print (' Output: ', attr) 7 # Time.sleep (3) 8 num+=1 9 lock.release () #释放线程锁10 time.sleep (3) One print (' Output done '. Center (10, ' I ')) 12 Star_time=time.time () #开始时间13 num=015 re_lilst=[] #定义一个列表16 for I in range: t1=threading. Thread (target=run,args= ('%s thread '%i)) #新建线程18 #t1. Setdaemon (True) #设置为守护进程 when the main thread is complete, the daemon stops T1.start () # Start thread re_lilst.append (t1) #不用JOIN, avoid blocking for serial print (Threading.current_thread (), Threading.active_count ()) # View Thread's master active thread #print (' Sub-thread '. Center (40, ' ☆ ')) print (' Number: ', num) for i in Re_lilst: #等待线程 completed I.join ( Print (' number: ', num)-print (' main thread '). Center (60, ' ◇ '), Threading.current_thread (), Threading.active_count ()) Den_ Time=time.time ()-star_time# total time of print (Den_time)
View Code
The daemon, equivalent to the subordinate of the main process, will stop when the main process is finished, regardless of whether the daemon executes or not!
1 Import time, threading 2 lock=threading. Lock () #定义一个线程锁变量 3 def Run (attr): 4 lock.acquire () #申请一个线程锁 5 global num 6 print (' Output: ', attr) 7 8 # Time.sleep (3) 9 num+=110 lock.release () #释放线程锁11 time.sleep (3) print (' Output complete '. Center (10, ' I ')) 13 Star_time=time.time () #开始时间15 num=017 re_lilst=[] #定义一个列表18 for I in range: t1=threading. Thread (target=run,args= ('%s thread '%i)) #新建线程20 T1.setdaemon (True) #设置为守护进程 when the main thread is complete, the daemon stops the T1.start () # Start thread re_lilst.append (t1) #不用JOIN, avoid blocking to serial print (Threading.current_thread (), Threading.active_count ()) # View Thread's master active thread #print (' Split thread '. Center (40, ' ☆ ')) + print (' number: ', num) # for I in Re_lilst: #等待线程 done I.join () Print (' Number: ', num)-print (' main thread '). Center (60, ' ◇ '), Threading.current_thread (), Threading.active_count ()) 31 Den_time=time.time ()-star_time# total time print (den_time)
View Code
The thread lock, which can not be used in PY3:
Lock=threading. Lock ()
Lock.acquire ()
Recursive locks for recursive threads
1 Import time, Threading 2 3 def Run (i): 4 print (' Output:-------', i) 5 lock.acquire () #申请锁 6 global NUM1 7 nu M1+=1 8 Time.sleep (0.1) 9 lock.release () #释放锁10 return num111 def run2 (i): Lock.acquire () #申请锁14 GL Obal num215 print (' Output: $ ', i) num2+=117 Time.sleep (0.1) lock.release () #释放锁19 return num220 def R Un3 (i): Lock.acquire () #申请锁23 res=run (i) print (' Output: 333 ', i) res2=run2 (i) time.sleep (0.1) p Rint (Res,res2) lock.release () #释放锁29 if __name__ = = ' __main__ ': Star_time=time.time () #开始时间 \33 Num1,nu m2=0,034 #lock =threading. Lock () #定义一个线程锁, in the case of a lock, the recursion error is lock=threading. Rlock () #定义一个递归锁36 Notoginseng for I in range: =threading #t1. Thread (target=run,args= ('%s thread '%i)) #新建线程39 t1=threading. Thread (target=run3,args= ('%s thread '%i)) #新建线程40 T1.start () #起动线程41 else:43 print (' Number of active threads: ', THREADING.A Ctive_count ()) #查看线程 number of active threads (in Threading.acti)Ve_count ()!=1: #不只一个线程, that is, to determine whether the remaining main thread #print (Threading.active_count ()) #查看线程 active thread Count pass49 else:50 print (' main thread :p ID, number of active threads '. Center (60, ' ◇ '), Threading.current_thread (), Threading.active_count ()) #51 den_time=time.time ()-star_ time# Total time Den_time print (num1,num2)
View Code
The semaphore is quite the same as 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 def Run (attr): semaphore.a Cquire () #申请信号量线程锁12 global num13 print (' Output: ', attr) time.sleep (1) semaphore.release () # Release the semaphore lock Star_time=time.time () #开始时间18 if __name__ = = ' __main__ ': semaphore=threading. Boundedsemaphore (4) #信号量 allow a maximum of several threads to run simultaneously (multiple locks) for the I in range: t1=threading. Thread (target=run,args= ('%s thread '%i)) #新建线程23 T1.start () #起动线程24 while Threading.active_count ()!=1: #不只一个线程 , that is, to determine whether the remaining main thread is pass27 else:28 print (' main thread '). Center (60, ' ◇ '), Threading.current_thread (), Threading.active_count ()) den_time=time.time ()-star_time# total time in print (den_time)
View Code
Event Thread Flag
Example of traffic lights
1 #! Usr/bin/env Python 2 #-*-coding:utf-8-*-3 # Author Calmyan 4 5 Import threading,time 6 7 event=threading. Event () #生成一个标示位对象 8 def Lighter (): # 9 count=0 #定义时间秒数10 Event.set () #设置标志位11 while True:12 if count> 9 and count<15: #设定为红灯13 event.clear () #清除标志位, print (' \033[41;1m turns red!\033[0m ') Elif C Ount>=15 and count<18: #为黄灯16 print (' \033[43;1m turns yellow!\033[0m ') elif count>=18:19 Event.set () #设置标志位20 print (' \033[42;1m into green light!\033[0m ') count=0# re-chronograph else:23 Print (' \033[42;1m green ...!! \033[0m ') time.sleep (1) count+=1# each second plus the Def car (name): while true:30 if event.i S_set (): #如果有标志 description for Green print (' [%s] on drive .... '%name ') time.sleep (1) else:34 PR Int (' [%s] in wait ... '%name) event.wait () #等待获取标志36 print (' green light on, [%s] continue ... '%name) "Notoginseng Tim E.slEEP (1) light=threading. Thread (Target=lighter,) #定义一个线程41 Light.start () #启动线程42 car1=threading. Thread (target=car,args= (' Hongqi sedan ',)) #生成一个汽车线程44 Car1.start ()
View Code
Queue producer Consumer Model
1 #! Usr/bin/env Python 2 #-*-coding:utf-8-*-3 # Author Calmyan 4 5 #队列 producer Consumer Model 6 7 import threading,time,queue 8
9 Q=queue. Queue () #创建一个队列10 def produ (name): #生产函数12 count=013 while true:14 bz=name+str (count) q.put (BZ) print (' [%s] ' produced, section [%s] [%s]g bun '% (NAME,COUNT,BZ)] + count+=118 time.sleep (1.5) def consump (name ): #消费者21 while true:22 i=q.get () #取23 print (' [%s] ' get bun [%s], and ate '% (name,i)) Time.sleep (0.5) 25 P1=threading. Thread (target=produ,args= (' Harry Bun Shop ')) #创建一个新线程 producer P2=threading. Thread (target=produ,args= (' linseed six Bun ')) #创建一个新线程 producer R1=threading. Thread (target=consump,args= (' Zhang San ')) #创建一个新线程 consumer r2=threading. Thread (target=consump,args= (' John Doe ',)) #创建一个新线程 consumer P1.start () P2.start () R1.start () R2.start ()
view code