在python中,发生异常时会自动释放锁吗?

Did*_*344 7 python locking

例如:

import threading

lock = threading.Lock()

with lock:
    some code that throws an exception
Run Code Online (Sandbox Code Playgroud)

这是假设抛出异常的代码没有包含在 try except 块中。

Mar*_*ers 7

将锁用作上下文管理器 ( with lock:) 的全部目的是让 Python 在发生异常时通知该锁对象。

所以是的,当发生异常时,锁会自行解锁,因为该with语句确保它收到异常通知。