因为有时它比围绕队列设计解决方案更实用,所以我想编写一个简单的包装器来使迭代器线程安全。到目前为止,我的灵感来自these https://stackoverflow.com/questions/1131430/are-generators-threadsafe topics https://stackoverflow.com/questions/1466676/create-a-wrapper-class-to-call-a-pre-and-post-function-around-existing-functions并提出了两个想法:
Idea 1
class LockedIterator(object):
def __init__(self, it):
self._lock = threading.Lock()
self._it = it.__iter__()
if hasattr(self._it, 'close'):
def close(self):
with self._lock:
self._it.close()
self.__setattr__('close', close)
def __iter__(self):
return self
def next(self):
with self._lock:
return self._it.next()
我不喜欢它的是,如果我必须指定所有可能的方法,它会变得有点冗长 - 好吧,我不能 - 例如生成器的特殊情况。另外,我可能还有一些其他具有更具体方法的迭代器,这些方法现在已被隐藏。
Idea 2
class LockedIterator(object):
def __init__(self, it):
self._lock = threading.Lock()
self._it = it.__iter__()
def __getattr__(self, item):
attr = getattr(self._it, item)
if callable(attr):
def hooked(*args, **kwargs):
with self._lock:
return attr(*args, **kwargs)
setattr(self, item, hooked)
return hooked
这更简洁,但它只能拦截调用,而不能,例如直接更改属性。 (现在隐藏这些属性以防止出现问题。)更重要的是,它使得 Python 不再将我的对象识别为迭代器!
在不创建泄漏抽象的情况下,使其适用于所有迭代器(甚至更好:所有对象)的最佳方法是什么?我不太担心不必要时的锁定,但如果你能想出一个解决方案来规避这个问题,那就太好了!