0

I would like to implement an entire dictionary subclass that is thread safe in every way - all the get and set methods. Currently, I am simply providing access to it via a helper function like this:

# 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

I think it might be better if I do it by subclassing the dict, since it would avoid awkward calls like getdict()["key"] = "value". The wrapper classes from collections library looks promising, but I am not sure which methods needs to be overridden in order to make it entirely safe. __getattr__ and __setattr__ would be two, but what about update? Are there any more? Is this even a good idea?

Renae Lider
  • 1,004
  • 7
  • 20
  • That is not an appropriate use of `with` .. the block is already over when the 'mydict' object is returned. – user2864740 Aug 26 '15 at 23:46
  • Anyway, 1) it is generally not reasonable to *only* replace / wrap the individual get/set operations because they do not extend a larger atomic context - ie. `if not x[y]: x[y] = z` is still *not* thread-safe; and 2) it is also pointless to wrap the individual get/set operations because, [*as individual operations*, they are already thread-safe](http://stackoverflow.com/questions/6953351/thread-safety-in-pythons-dictionary). – user2864740 Aug 26 '15 at 23:54
  • @user2864740 Took me a while to think it through... now I get it. That lock is as useless as a white crayon. I should be using something like a queue mechanism... I think. Hmmmm...don't know (brain freeze) – Renae Lider Aug 26 '15 at 23:56
  • There is a discussion about and solution for this at http://stackoverflow.com/questions/8487673/how-would-you-make-this-python-dictionary-thread-safe –  Aug 27 '15 at 00:00

0 Answers0