我在python中有一个接受互斥体列表的类。然后,它将对该列表进行排序,并使用__enter__()
和__exit__()
以特定顺序锁定/解锁所有互斥锁,以防止死锁。
当前,该类为我们节省了很多潜在的死锁麻烦,因为我们只能以RAII样式调用它,即:
self.lock = SuperLock(list_of_locks)
# Lock all mutexes.
with self.lock:
# Issue calls to all hardware protected by these locks.
我们想公开此类提供RAII样式的API的方法,以便在以某种方式调用时,一次只能锁定一半的互斥锁,即:
self.lock = SuperLock(list_of_locks)
# Lock all mutexes.
with self.lock:
# Issue calls to all hardware protected by these locks.
# Lock the first half of the mutexes in SuperLock.list_of_locks
with self.lock.first_half_only:
# Issue calls to all hardware protected by these locks.
# Lock the second half of the mutexes in SuperLock.list_of_locks
with self.lock.second_half_only:
# Issue calls to all hardware protected by these locks.
有没有办法提供这种类型的功能,以便我可以调用with self.lock.first_half_only
或with self.lock_first_half_only
()
向用户提供简单的API?我们希望将所有这些功能都放在一个类中。
谢谢。
是的,您可以获取此界面。在with语句的上下文中将要输入/退出的对象是resolve属性。因此,您可以继续将上下文管理器定义为上下文管理器的属性:
from contextlib import ExitStack # pip install contextlib2
from contextlib import contextmanager
@contextmanager
def lock(name):
print("entering lock {}".format(name))
yield
print("exiting lock {}".format(name))
@contextmanager
def many(contexts):
with ExitStack() as stack:
for cm in contexts:
stack.enter_context(cm)
yield
class SuperLock(object):
def __init__(self, list_of_locks):
self.list_of_locks = list_of_locks
def __enter__(self):
# implement for entering the `with self.lock:` use case
return self
def __exit__(self, exce_type, exc_value, traceback):
pass
@property
def first_half_only(self):
return many(self.list_of_locks[:4])
@property
def second_half_only(self):
# yo dawg, we herd you like with-statements
return many(self.list_of_locks[4:])
创建并返回新的上下文管理器时,可以使用实例中的状态(即self
)。
用法示例:
>>> list_of_locks = [lock(i) for i in range(8)]
>>> super_lock = SuperLock(list_of_locks)
>>> with super_lock.first_half_only:
... print('indented')
...
entering lock 0
entering lock 1
entering lock 2
entering lock 3
indented
exiting lock 3
exiting lock 2
exiting lock 1
exiting lock 0
编辑:lock
上面显示的生成器上下文管理器的基于类的等效项
class lock(object):
def __init__(self, name):
self.name = name
def __enter__(self):
print("entering lock {}".format(self.name))
return self
def __exit__(self, exce_type, exc_value, traceback):
print("exiting lock {}".format(self.name))
# If you want to handle the exception (if any), you may use the
# return value of this method to suppress re-raising error on exit
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句