Threading
Ciobanu Vladimir
psycho at tex.ro
Wed Nov 14 10:11:30 EST 2001
psycho at tex.ro (Ciobanu Vladimir) wrote in message news:<f2567110.0111130957.3631ad8f at posting.google.com>...
> 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.
I thank Skip Montanaro for his help, but I still didn't get a clear
answer. This is my fault since I wasn't clear enough. Skip was kind
enough to remind me that if two threads call __getitem__, another
thread may get between, call __setitem__ causing the two
supposed-to-be identical values got from __getitem__ to be different.
I am quite aware of this. Since this DataBase program is going to be
quite often updated, I have a better solution.
I will add a property to DataBase, namely __readonly. If one user
opens it as __readonly, calling function members that change the data
in the DataBase ( such as __setitem__) then an exception is raised. I
will allow one, and only one user to modify the database at a time.
Plus if one is modifyiny, none can read.
I had to add this new information in order not to recive the same
"someone may change the data" kind of answer. I am trying to be more
clear/specific. The point is:
If I'm calling only functions such as __getitem__ ( and maybe
querry which mainly calls .has_key( key)), is it safe not to add locks
to these functions ?
I would ask you not to answer if you're not sure about the answer.
This is quite important, since it would be a major draw-back if two
users couldn't read at the same time. It doesn't make sence, either.
Thank you in advance,
Vladimir
More information about the Python-list
mailing list