正如每个优秀的开发人员所熟知的那样,混合异常管理和线程安全调用总是微妙的。
我第一次在 Python 中处理这种情况。 我知道在 Python 2.5 及更高版本中,可以使用 with 语句,如下所示:
When used with a lock, this statement automatically acquires the lock before entering the block, and releases it when leaving the block:
from __future__ import with_statement # 2.5 only with lock: ... access shared resource
考虑这个示例代码:
from __future__ import with_statement
import threading
def static_vars(**kwargs):
def decorate(func):
for k in kwargs:
setattr(func, k, kwargs[k])
return func
return decorate
lock = threading.Lock();
@static_vars(counter = 0)
def ts_increment():
with lock:
try:
// something else, also thread-safe
ts_increment.counter += 1
except:
raise
如果 raise 语句捕获并重新抛出异常,是否会释放锁?
请您参考如下方法:
是的,如果在 with 语句中引发异常,锁将被释放。
>>> import threading
>>> l = threading.Lock()
>>> with l:
raise
Traceback (most recent call last):
File "<pyshell#4>", line 2, in <module>
raise
RuntimeError: No active exception to reraise
>>> l.acquire() # see if we can lock the lock.
True
旁注:如果您查看 with 语句的工作原理,l.__enter__ 在进入语句时被调用,而 l.__exit__ 总是在退出时被调用 with错误信息或 None。参见 pep 343 “规范:‘with’语句”部分。
