在看programing python 4th,第5张parallel system tool 192页开始,书中讲到thread知识,以下做个笔记,以便后期学习
1.主线程执行,开启5个子线程进行计数,没有使用mutex锁住,所以线程没有lock住资源,每个线程对全局变量的操作错乱,结果如下:
1 """ 2 synchronize access to stdout: because it is shared global 3 thread outputs may be intermixed if not syschronized 4 """ 5 import thread,time 6 global num #global var to be used by many threads 7 num=0 8 9 def cnt(id,count): # function run in threads 10 for i in range(count): 11 global num 12 #mutex.acquire() # lock the share var before execute 13 num +=1 14 time.sleep(0.5) # simulate read work 15 print('[%s] num= %s ' %(id,num)) #print isn't interrupted now 16 #mutex.release() #release the lock for the other thread 17 18 if __name__ =="__main__": 19 #mutex=thread.allocate_lock() #make a global mutex for lock 20 for i in range(5): #spawm 5 threads 21 thread.start_new_thread(cnt,(i,3)) #start threads 22 time.sleep(8) # wait for spawn thread work done,don't exit too early 23 24 print('main thread exitting')
2.把mutex 注释打开,有了mutex变量,每一个线程进入都会独占num变量,结果如下:
1 """ 2 synchronize access to stdout: because it is shared global 3 thread outputs may be intermixed if not syschronized 4 """ 5 import thread,time 6 global num #global var to be used by many threads 7 num=0 8 9 def cnt(id,count): # function run in threads 10 for i in range(count): 11 global num 12 mutex.acquire() # lock the share var before execute 13 num +=1 14 time.sleep(0.5) # simulate read work 15 print('[%s] num= %s ' %(id,num)) #print isn't interrupted now 16 mutex.release() #release the lock for the other thread 17 18 if __name__ =="__main__": 19 mutex=thread.allocate_lock() #make a global mutex for lock 20 for i in range(5): #spawm 5 threads 21 thread.start_new_thread(cnt,(i,3)) #start threads 22 time.sleep(8) # wait for spawn thread work done,don't exit too early 23 24 print('main thread exitting')
3.如果把time.sleep(6)注释掉或者子线程没有执行完毕,而主线程sleep的时间一到,主线程直接退出而不等待子线程执行完毕,结果如下:
a.主线程不等待,则直接退出
b.主线程只等待3s,而5个子线程需要7.5s,所以num只计数5.
4.设定有效等待时间和锁之后,主线程等待所有子线程执行结束才退出,结果如下:
6.无需在主线程设置等待时间,而是设定单独的锁或者变量来记录每个子线程的执行状态,每执行完一个线程,设定状态锁,然后在主线程判断所有状态锁的状态即可
1 """ 2 used mutexex to know when threads are done in parent/main thread, 3 instead of time.sleep;lock stdout to avoid comingled prints 4 """ 5 import thread,time 6 global num 7 num =0 8 9 def cnt(id,count): 10 for i in range(count): 11 global num 12 stdoutmutex.acquire() 13 num +=1 14 time.sleep(0.5) 15 print('[%s] num= %s time:[%s] ' %(id,num,time.ctime())) #print isn't interrupted now 16 stdoutmutex.release() 17 #exitmutexs[id].acquire() # signal main thread 18 exitFlags[id] = True #signal main thread 19 20 if __name__ =="__main__": 21 stdoutmutex = thread.allocate_lock() #make a global mutex for lock 22 #exitmutexs = [thread.allocate_lock() for i in range(5)] 23 exitFlags=[False]*5 24 for i in range(5): #spawm 5 threads 25 thread.start_new_thread(cnt,(i,3)) #start threads 26 #for mutex in exitmutexs: 27 # while not mutex.locked(): 28 # pass 29 while False in exitFlags:pass 30 print('main thread exitting')