clifford.wells at comcast.net
Wed Oct 13 13:51:40 CEST 2004
On Wed, 2004-10-13 at 07:33 -0400, Jeremy Jones wrote:
> Ajay wrote:
> >what would happen if i try to access a variable locked by another thread? i
> >am not trying to obtain a lock on it, just trying to access it.
> I may be wrong, but I'm not sure you can lock a variable.
I assumed the OP was referring to threading.Lock/RLock. But maybe not?
> Actually, you
> probably could do something like "locking a variable" with
> __getattr__(), __setattr(), and __delattr__() and sprinkling gently with
> locks. The locking mechanisms in the thread and threading libraries
> (allocate_lock() and Lock() respectively) lock sections of code. When
> you hit a section of code you want locked, you do a <lock>.acquire() and
> when you want to unlock an acquired lock, you do a <lock>.release(). If
> you have a variable in a section of code that you have locked, you can
> still see/smell/taste/touch/modify it from another thread if you can
> access it. So, if you've passed an object to multiple threads and one
> has acquired a lock to a specific section of code, another thread can't
> enter that section of code until the first releases the lock. But, if
> you have the same object in a different section of code, you can execute
> that unlocked code that contains/points-to the object.
I usually just use a class with lock/release methods that invoke the
appropriate threading.Lock call, but your idea is interesting as it can
help avoid forgetting to acquire the lock. In fact, with an appropriate
set of methods for accessing/modifying etc, it seems possible to ensure
the lock is released from within the class as well. Doing it with
properties (which I haven't played with to-date) seems even more
interesting. I may have to whip up a class in this vein to give it a
Cliff Wells <clifford.wells at comcast.net>
More information about the Python-list