码迷,mamicode.com
首页 > 其他好文 > 详细

Thread and shared lock

时间:2015-09-12 13:28:53      阅读:247      评论:0      收藏:0      [点我收藏+]

标签:

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)
View Code

技术分享

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)
View Code

技术分享

3.如果把time.sleep(6)注释掉或者子线程没有执行完毕,而主线程sleep的时间一到,主线程直接退出而不等待子线程执行完毕,结果如下:

a.主线程不等待,则直接退出

技术分享

b.主线程只等待3s,而5个子线程需要7.5s,所以num只计数5.

技术分享

4.设定有效等待时间和锁之后,主线程等待所有子线程执行结束才退出,结果如下:

技术分享

 

Thread and shared lock

标签:

原文地址:http://www.cnblogs.com/lxk613/p/4802847.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!