码迷,mamicode.com
首页 > 编程语言 > 详细

多线程中锁的概念python

时间:2015-03-03 18:42:17      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:python   线程   

多线程中锁的概念python

好几个人问我给资源加锁是怎么回事,其实并不是给资源加锁, 而是用锁去锁定资源,你可以定义多个锁, 像下面的代码, 当你需要独占某一资源时,任何一个锁都可以锁这个资源

就好比你用不同的锁都可以把相同的一个门锁住是一个道理

 

#coding: utf-8
import  threading  
import  time  
   
counter = 0
counter_lock = threading.Lock() #只是定义一个锁,并不是给资源加锁,你可以定义多个锁,像下两行代码,当你需要占用这个资源时,任何一个锁都可以锁这个资源
counter_lock2 = threading.Lock() 
counter_lock3 = threading.Lock()

#可以使用上边三个锁的任何一个来锁定资源
 
class  MyThread(threading.Thread):#使用类定义thread,继承threading.Thread
     def  __init__(self,name):  
        threading.Thread.__init__(self)  
        self.name = "Thread-" + str(name)
     def run(self):   #run函数必须实现
         global counter,counter_lock #多线程是共享资源的,使用全局变量
         time.sleep(1);  
         if counter_lock.acquire(): #当需要独占counter资源时,必须先锁定,这个锁可以是任意的一个锁,可以使用上边定义的3个锁中的任意一个
            counter += 1   
            print "I am %s, set counter:%s"  % (self.name,counter)  
            counter_lock.release() #使用完counter资源必须要将这个锁打开,让其他线程使用
            
if  __name__ ==  "__main__":  
    for i in xrange(1,101):  
        my_thread = MyThread(i)
        my_thread.start()



 

 

多线程中锁的概念python

标签:python   线程   

原文地址:http://blog.csdn.net/kobeyan/article/details/44039831

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