Python多线程编程(六):可重入锁RLock

WBOY
Release: 2016-06-06 11:23:25
Original
1596 people have browsed it

考虑这种情况:如果一个线程遇到锁嵌套的情况该怎么办,这个嵌套是指当我一个线程在获取临界资源时,又需要再次获取。

根据这种情况,代码如下:

代码如下:


'''
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


之后就直接挂起了,这种情况形成了最简单的死锁。

那有没有一种情况可以在某一个线程使用互斥锁访问某一个竞争资源时,可以再次获取呢?在Python中为了支持在同一线程中多次请求同一资源,python提供了“可重入锁”:threading.RLock。这个RLock内部维护着一个Lock和一个counter变量,counter记录了acquire的次数,从而使得资源可以被多次require。直到一个线程所有的acquire都被release,其他的线程才能获得资源。上面的例子如果使用RLock代替Lock,则不会发生死锁:

代码只需将上述的:

代码如下:


mutex = threading.Lock()


替换成:

代码如下:


mutex = threading.RLock()


即可。
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!