为什么需要可重入锁
import threading
lock = threading.RLock()
def f():
with lock:
g()
h()
def g():
with lock:
h()
do_something1()
def h():
with lock:
do_something2()
def do_something1():
print('do_something1')
def do_something2():
print('do_something2')
# Create and run threads as follows
try:
threading.Thread( target=f ).start()
threading.Thread( target=f ).start()
threading.Thread( target=f ).start()
except Exception as e:
print("Error: unable to start thread")
每个thread都运行f(),f()获取锁后,运行g(),但g()中也需要获取同一个锁。如果用Lock,这里多次获取锁,就发生了死锁。
但我们代码中使用了RLock。在同一线程内,对RLock进行多次acquire()操作,程序不会堵塞。

本文通过具体示例解释了为何需要使用可重入锁。在多线程环境下,普通锁可能会导致死锁问题,而可重入锁允许同一线程多次获取同一把锁,有效避免了这一情况。
&spm=1001.2101.3001.5002&articleId=82586434&d=1&t=3&u=cd710c85e06c4ec097d33d693440cfc5)
903

被折叠的 条评论
为什么被折叠?



