考虑这种状况:若是一个线程遇到锁嵌套的状况该怎么办,这个嵌套是指当我一个线程在获取临界资源时,又须要再次获取。python
根据这种状况,代码以下:ide
Python代码ui
- '''''
- Created on 2012-9-8
- @author: walfred
- @module: thread.ThreadTest6
- '''
- import threading
- import time
- counter = 0
- mutex = threading.Lock()
- class MyThread(threading.Thread):
- def __init__(self):
- threading.Thread.__init__(self)
- def run(self):
- global counter, mutex
- time.sleep(1);
- if mutex.acquire():
- counter += 1
- print "I am %s, set counter:%s" % (self.name, counter)
- if mutex.acquire():
- counter += 1
- print "I am %s, set counter:%s" % (self.name, counter)
- mutex.release()
- mutex.release()
- if __name__ == "__main__":
- for i in range(0, 200):
- my_thread = MyThread()
- my_thread.start()
这种状况的代码运行状况以下:线程
I am Thread-1, set counter:1资源
以后就直接挂起了,这种状况造成了最简单的死锁。it
那有没有一种状况能够在某一个线程使用互斥锁访问某一个竞争资源时,能够再次获取呢?在Python中为了支持在同一线程中屡次请求同一资源,python提供了“可重入锁”:threading.RLock。这个RLock内部维护着一个Lock和一个counter变量,counter记录了acquire的次数,从而使得资源能够被屡次require。直到一个线程全部的acquire都被release,其余的线程才能得到资源。上面的例子若是使用RLock代替Lock,则不会发生死锁:class
代码只需将上述的:thread
Python代码import
- mutex = threading.Lock()
替换成:require
Python代码
- mutex = threading.RLock()
便可。