在Python中混合使用异常管理和线程安全调用

在Python中混合使用异常管理和线程安全调用,python,multithreading,exception,exception-handling,Python,Multithreading,Exception,Exception Handling,每个优秀的开发人员都知道,混合异常管理和线程安全调用始终是一件微妙的事情 这是我第一次在Python中处理这种场景。 我知道在Python 2.5及更高版本中,可以使用with语句,如下所示: 当与锁一起使用时,此语句自动获取锁 在进入块之前,并在离开块时将其释放: from __future__ import with_statement # 2.5 only with lock: ... access shared resource 考虑到此示例代码: from __future

每个优秀的开发人员都知道,混合异常管理和线程安全调用始终是一件微妙的事情

这是我第一次在Python中处理这种场景。 我知道在Python 2.5及更高版本中,可以使用
with
语句,如下所示:

当与锁一起使用时,此语句自动获取锁 在进入块之前,并在离开块时将其释放:

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
导入线程 >>>l=线程。锁() >>>与l: 提升 回溯(最近一次呼叫最后一次): 文件“”,第2行,在 提升 RuntimeError:没有活动异常可重新启动 >>>获取()#看看我们是否能锁上锁。 真的 旁注:如果查看with语句的工作情况,则在输入语句时调用
l.\uuuu enter\uuuu
,在退出时总是调用
l.\uu exit\uuuu
,并显示错误信息或
None
。请参阅“规范:with”语句一节