哪个方法需要重写以使dict子类线程安全?

时间:2015-08-26 23:44:08

标签: python multithreading dictionary thread-safety

我想实现一个完整的字典子类,它在各方面都是线程安全的 - 所有get和set方法。目前,我只是通过这样的辅助函数提供对它的访问:

# Don't access directly (I am not a big fan of name mangling)
mydict = dict()
lock = threading.Rlock()

def getdict():
    """Safe way to access the dict."""
    with lock:
        return mydict

我认为通过继承dict可能会更好,因为它可以避免像getdict()["key"] = "value"这样的尴尬调用。来自collections库的包装类看起来很有希望,但我不确定需要覆盖哪些方法才能使其完全安全。 __getattr____setattr__会是两个,但是update呢?还有吗?这甚至是个好主意吗?

0 个答案:

没有答案