Accessing thread variables

Alex Martelli aleaxit at yahoo.com
Wed Feb 19 12:13:55 CET 2003


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