锁与可重入锁(以Python为例)

本文通过具体示例解释了为何需要使用可重入锁。在多线程环境下,普通锁可能会导致死锁问题,而可重入锁允许同一线程多次获取同一把锁,有效避免了这一情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

为什么需要可重入锁

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()操作,程序不会堵塞。

更多

  1. https://blog.youkuaiyun.com/ybdesire/article/details/80294638
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值