标签:
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\n‘ %(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\n‘ %(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.设定有效等待时间和锁之后,主线程等待所有子线程执行结束才退出,结果如下:
标签:
原文地址:http://www.cnblogs.com/lxk613/p/4802847.html