例如:
import threading
lock = threading.Lock()
with lock:
some code that throws an exception
Run Code Online (Sandbox Code Playgroud)
这是假设抛出异常的代码没有包含在 try except 块中。
将锁用作上下文管理器 ( with lock:) 的全部目的是让 Python 在发生异常时通知该锁对象。
所以是的,当发生异常时,锁会自行解锁,因为该with语句确保它收到异常通知。
| 归档时间: |
|
| 查看次数: |
2705 次 |
| 最近记录: |