[Edu-sig] Properties use case

David Reed dreedmac at columbus.rr.com
Sat Mar 25 15:10:22 CET 2006

On Mar 25, 2006, at 8:33 AM, Arthur wrote:

>>> -----Original Message-----
>>> From: Laura Creighton [mailto:lac at strakt.com]
>>> Sent: Saturday, March 25, 2006 7:16 AM
>>> To: Arthur
>>> Ok, so it does matter.  Are you locking your complex number
>>> before modifying it?
> Just to generalize the issue, so that I know, realy, what we are  
> talking
> about, can we discuss my circle instead of my complex object.
> It has a center, a radius, and a matrix describing its orientation  
> in space.
> I would like all to be in sync and recalculated, based on changes  
> to the
> position of any other objects on which its center, its radius, or its
> orientation in space is dependent, *before* it redraws itself.
> No I do not lock my circle.
> Art

I think you are saying you don't quite understand when locks are  
needed. My apologies if this is not  what you are saying, but here is  
a short explanation of when locks are needed.

Whenever you have multiple threads that are using the same data  
structure you need a lock to ensure that only one thread is accessing  
it at a time. This is not an issue if none of the threads are  
modifying the object (which is the case with immutable objects since  
they cannot be modified). If at least one thread is modifying the  
object you need a lock around every access of the object otherwise  
you could have one thread start updating the object, be interrupted  
by the scheduler and another thread could then access the object that  
is now in an inconsistent state because the modification by the other  
thread had not completed.

Consider two different threads both executing the code (with the same  
y = x
y = y + 1
x = y

If one thread executes y = x and then is interrupted by the  
scheduler, and the other thread now executes all three statements,  
and then the first thread completes the final two statements, x is  
now just one more than it was before, even though both threads added  
one to it (i.e., it should be two more than it was).

The solution to this each thread does:
y = x
y = y + 1
x = y

This will not allow the second thread to start the code if the first  
thread has started it but not yet finished it.

Again with immutable objects, this is not an issue. Also, as I  
understand it, Python's Queue class in the Queue module is thread  
safe (i.e., it essentially takes care of the locking for you).


More information about the Edu-sig mailing list