【发布时间】:2018-11-29 20:12:02
【问题描述】:
背景
我在 python 中有一个类,它接收一个互斥体列表。然后它对该列表进行排序,并使用__enter__() 和__exit__() 按特定顺序锁定/解锁所有互斥锁以防止死锁。
该类目前为我们省去了很多潜在死锁的麻烦,因为我们可以在 RAII style 中调用它,即:
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?我们希望将所有这些功能保留在一个类中。
谢谢。
【问题讨论】:
标签: python python-2.7 class python-2.x contextmanager