Threading

Ciobanu Vladimir psycho at tex.ro
Tue Nov 13 12:57:21 EST 2001


Consider this:

class DataBase:
   def __init__( self):
      self.__dictionary = {}
   def __getitem__( self, key):
      return self.__dictionary[key]
   def __setitem__( self, key, value):
      self.__dictionary[key] = value

   This is a very simplified version of the class. It only contains
enough stuff to ask my question. ( I mentioned this so I wouldn't get
answers such as "Why the hell aren't you using a plain dictionary ?")
   Now, consider that this DataBase class is to be used in a real
world program, specifically in a threaded world. This would imply I
use locks, which brings me to the actual question. Unfortunately the
Python Library Reference isn't clear enough ( to me, at least) about
this particular detail:
   Is it safe to call __getitem__ without placing locks ?
   To make it more clear, it is quite obvious that allowing two
threads to simultaneously write ( call __setitem__) isn't desired; but
what about reading ( call __getitem__). Are there any guarantees that
threads don't interfere ( read things that aren't there, resolve in
undefined behaviour in any way) when reading data ?
    My first guess would be that I shouldn't be adding locks to
__getitem__, but this depends on the implementation so it's quite
tricky.

PS: I'd love if Python added a const modifier for methods at least (
if not for objects too).

                                   Thanks in advance.



More information about the Python-list mailing list