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

yipeiwu_com6年前Python基础

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

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

复制代码 代码如下:

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

即可。

相关文章

Python的collections模块中namedtuple结构使用示例

namedtuple 就是命名的 tuple,比较像 C 语言中 struct。一般情况下的 tuple 是 (item1, item2, item3,...),所有的 item 都只能...

python清除字符串里非字母字符的方法

本文实例讲述了python清除字符串里非字母字符的方法。分享给大家供大家参考。具体如下: s = "hello world! how are you? 0" # Short...

Python中的几种矩阵乘法(小结)

一.  np.dot() 1.同线性代数中矩阵乘法的定义。np.dot(A, B)表示: 对二维矩阵,计算真正意义上的矩阵乘积。 对于一维矩阵,计算两者的内积。 2...

Python合并多个Excel数据的方法

Python合并多个Excel数据的方法

安装模块 1、找到对应的模块   http://www.python-excel.org/ 2、用pip install 安装 pip install xlrd p...

TensorFlow2.0:张量的合并与分割实例

** 一 tf.concat( ) 函数–合并 ** In [2]: a = tf.ones([4,35,8]) In [3]:...