1、基本概念

  如果想让只有拿到锁的线程才能释放该锁,那么应该使用RLock()对象。当需要在类外面保证线程安全,又要在类内使用同样方法的时候RLock()就很使用。

  RLock叫做Reentrant Lock,就是可以重复进入的锁,也叫递归锁。这种锁对比Lock有三个特点:1、谁拿到锁,谁释放;2、同一线程可以多次拿到该锁;3、acquire多少次就必须release多少次,只有最后一次release才能改变RLock的状态为unlocked。

 

2、RLock示例代码

# coding:utf-8

import threading
import time

class Box(object):
    lock = threading.RLock()

    def __init__(self):
        self.total_items = 0

    def execute(self, n):
        Box.lock.acquire()
        self.total_items += n
        Box.lock.release()

    def add(self):
        Box.lock.acquire()
        self.execute(1)
        Box.lock.release()

    def remove(self):
        Box.lock.acquire()
        self.execute(-1)
        Box.lock.release()

def adder(box, items):
    while items > 0:
        print("adding 1 item in the box")
        box.add()
        time.sleep(1)
        items -= 1
def remover(box, items):
    while items > 0:
        print("removing 1 item in the box")
        box.remove()
        time.sleep(1)
        items -= 1

if __name__ == "__main__":
    items = 5

    print("putting %s items in the box" %items)
    box = Box()
    t1 = threading.Thread(target=adder, args=(box, items))
    t2 = threading.Thread(target=remover, args=(box, items))

    t1.start()
    t2.start()

    t1.join()
    t2.join()
    print("%s items still remain in the box " % box.total_items)

      上述代码中adder()和remover()两个函数在Box类内操作items,即调用Box类的方法:add()和remove()。每一次方法调用,都会有一次拿到资源然后释放资源的过程。至于lock()对象,RLock()对象有acquire()和release()方法可以拿到或释放资源;每一次方法调用中,都有一下操作:

    Box.lock.acquire()

    do something

    Box.lock.release()

      运行结果如下:

      

      

 

posted on 2018-10-11 11:01  杜先生的博客  阅读(1087)  评论(0编辑  收藏  举报