stupid thread question

Gordon McMillan gmcm at hypernet.com
Mon Jun 12 21:33:20 EDT 2000


Michael Vanier: 

>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.  


Let me guess. You did something like make "flag" a module level global, and 
then did "from ... import *" in the other.

If you had referenced "module.flag", all would have worked. But that 
stinks, too. Your thread should have a flag member, and the parent thread 
should set it (through a setter, if you really want to be virtuous <wink>). 
That way the flag becomes part of the thread's API, instead of a bass-
ackwards dependency.


> 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? 

Aahz is correct (as usual). It has to do with assignment and immutability. 
To see assignment to any immutable (not in your global or local namespace), 
you have to see the immutable through some larger context. Say, a module 
namespace, or (as you did) through a container object.

- Gordon



More information about the Python-list mailing list