聊聊Lock RLock

462 阅读1分钟

官方定义

lock: 原始锁,不属于特定线程,即一个线程加锁,可以由另一个线程解锁
rlock: 可重入锁,属于特定线程,也就是当前线程才能释放本线程的锁,解铃还需系铃人

相同点:
lock、rlock支持上下文管理器的,可以用with来代替acquire release操作

常见用法

  1. lock可以由其他线程释放
import threading

lock = threading.Lock()
lock.acquire()

def func():
    lock.release()
    print("lock is released")

t = threading.Thread(target=func)
t.start()
  1. with上下文管理器
import threading
import time

lock1 = threading.RLock()

def outer():
    with lock1:
        print("outer function:%s" % threading.current_thread())
 

if __name__ == "__main__":
    t1 = threading.Thread(target=outer)
    t2 = threading.Thread(target=outer)
    t1.start()
    t2.start()
  1. rlock什么时候用
import threading
import time

lock1 = threading.RLock()


def inner():
    with lock1:
        print("inner1 function:%s" % threading.current_thread())


def outer():
    print("outer function:%s" % threading.current_thread())
    with lock1:
        inner()


if __name__ == "__main__":
    t1 = threading.Thread(target=outer)
    t2 = threading.Thread(target=outer)
    t1.start()
    t2.start()

一般像这种锁的嵌套,普通的lock是无法满足的,因为lock只能acquire一次,使用完成后需要release。只有这种rlock才能可重入,否则使用lock就会出现死锁。