Accessing thread variables

Lukas Kubin kubin at opf.slu.cz
Wed Feb 19 07:17:06 EST 2003


Yes, I've placed just an example code for simplicity and did those 2 
errors in it. But I've not done them in the real code. Stuart Bishop 
answered I should use the i.join() function before accessing the 
i.varToReturn variable to ensure the thread has finished. It works.

You suggested to use the Queue module. But I don't need to access a 
changing variable from inside each thread. I just want to access the 
variable storing value returned by myAction() from outside, like the 
print i.varToReturn. Should I use the Queue module anyway?

Thanks

lukas

Alex Martelli wrote:
> Lukas Kubin wrote:
> 
> 
>>What's the best way to access a thread's variable?
>>Let's say I have thread:
>>
>>class MyThread(threading.Thread):
>>   def __init__(self):
>>     threading.Thread.__init__(self)
>>     self.varToReturn = ""
>>     self.start()
>>
>>   def run(self):
>>     self.varToReturn = myAction()
>>
>>   def myAction():
>>     string = "hello"
>>     return string
>>
>>And I call the thread:
>>
>>i = MyThread()
>>print i.varToReturn
>>
>>This returns nothing (the empty string) instead of "hello".
>>What am I doing bad?
> 
> 
> You have a race condition between the main thread reading
> i.varToReturn and the subthread setting it to the result
> of function myAction (which CANNOT be as you coded it here,
> of course -- it must be a global function off somewhere
> else -- because you're NOT calling self.myAction() and
> if you were you'd fail because method myAction of class
> MyThread is miscoded, lacking the self parameter -- note
> that in general you should post the code you're running,
> and you're not doing this here, clearly).
> 
> The simplest way for threads to communicate is via objects
> of class Queue from standard library module Queue.  While
> it's possible to dress this up via a clever __getattr__
> and a lot of trickery to look like attribute access, it
> would be a very bad way to proceed -- black magic and all
> that.  Just use an explicit Queue when one thread needs
> results that another thread is computing.
> 
> 
> Alex
> 





More information about the Python-list mailing list