Bernard Lebel wrote: > Hello, > > I have an instance attribute (a few characters string) that two > separate threads may change, potentially both at the same time. > My program doesn't implement thread safety for this particular task. > > So far I have never run into issues with this, but I have been reading > about data corruption when two threads try to write to the same data > at once. I'm just about to deploy my program over 70 computers, so now > I'm having some seconds thoughts of dread. > > Should changing instance attributes be done with maximum thread > safety? That is, to use some sort of queue (like the Queue class) so > that all changes to the attribute goes through this queue and can > never happen concurrently?
Are you talking about a simple assignment like self.x = 'abc'? If there is no Python code invoked by setting the attribute, I think the attribute will always be correctly set to the value from one of the threads. In this case the setattr will happen in a single Python byte code and it will be atomic. In other words, both of the sets will succeed and which ever one happens last will persist. If you *care* which of the setattrs succeeds, then you have a race condition that you need to address somehow. If Python code is invoked by setting the attribute then you could have a problem. This could happen, for example, if the attribute is a property, if the class (or one of its base classes) overrides __setattr__(), and probably in several other ways I haven't thought of. In this case you need to look at whether the Python code is thread-safe. Kent _______________________________________________ Tutor maillist - [email protected] http://mail.python.org/mailman/listinfo/tutor
