def singleton_contextmanager(func):
class CtxManager():
def __init__(self, func):
self.count = 0
self.func_cm = contextmanager(func)
self._lock = RLock()
def __enter__(self):
with self._lock:
if self.count == 0:
self.ctm = self.func_cm()
self.obj = self.ctm.__enter__()
self.count += 1
def __exit__(self, *args):
with self._lock:
self.count -= 1
if self.count > 0:
return
self.ctm.__exit__(*sys.exc_info())
del self.ctm
del self.obj
return CtxManager(func)
评论列表
文章目录