stupid thread question

Aahz Maruch aahz at netcom.com
Mon Jun 12 18:47:37 EDT 2000


In article <jl7lbu4jdf.fsf at endor.bbb.caltech.edu>,
Michael Vanier  <mvanier at endor.bbb.caltech.edu> wrote:
>
>I wrote a little python script using the thread module the other day.  I
>wanted to be able to set a flag in the parent thread that would be read in
>the child thread.  So I set a flag variable (an integer in this case) in the
>parent, created the child thread, and then checked the value of the flag
>every time through a loop in the child thread to see if it had changed.  It
>turns out that the child thread apparently made a copy of the flag, because
>when it changed in the parent it didn't change in the child.
>
>To fix this, I changed the flag to be a list with one integer element.  Now,
>when I change the list element in the parent, the child sees it too.  I
>gather that what this means is that there is a fundamental distinction
>between atomic types like integers and reference types like lists or
>dictionaries.  However, since python treats everything as a reference this
>seems inconsistent to me.  So what I want to know is: what is the cause of
>this behavior, and what is the justification for it?  Or could it be a bug?

This actually has nothing to do with threads and everything to do with
the distinction between global and local variables, plus the distinction
between mutable and immutable objects.  Generally speaking, it's better
practice for what you're doing to create a class instance, pass it in
to the thread, and read/modify class attributes.  Note that you'll
likely want to use a semaphore to make sure that you don't get into
situations where you're reading the variable in one thread while you're
setting it in another.
--
                      --- Aahz (Copyright 2000 by aahz at netcom.com)

Androgynous poly kinky vanilla queer het    <*>     http://www.rahul.net/aahz/
Hugs and backrubs -- I break Rule 6

"real love can't be explained by simplistic platitudes."  --piranha



More information about the Python-list mailing list