[Tutor] Changing instance attributes in different threads
Bernard Lebel
3dbernard at gmail.com
Mon Feb 6 23:29:59 CET 2006
hi Kent,
See [Bernard] below.
On 2/6/06, Kent Johnson <kent37 at tds.net> wrote:
> 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'?
[Bernard] Yes.
> 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.
[Bernard] This is where I'm getting a bit confused..... changing the
attribute doesn't automatically invoke code. But at various points in
the program, the value of this attribute is tested, and if matches
certain strings, a function is called.
Example:
- Class instance Bernard has attribute "name", whose value is "bernard".
- A function in a thread tests the value of "name". If "name" ==
"bernard", do nothing.
- A function in another thread, for some reason, changes "name" to "bob".
- The first function, few moments later, tests again the value of
"name". It see that the value has changed from "bernard" to "bob", and
this change causes the function to take an action.
Is that what you mean by "invoking" code?
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.
[Bernard] There is nothing of that sort in my program. Classes are all
"independent", that is, are not derived from another class. A handful
of their attributes like the one I described are changed at various
moments, only to be tested by other functions, in order to control the
flow of execution.
Bernard
More information about the Tutor
mailing list