[python-win32] Geting values from a thread
Tim Roberts
timr at probo.com
Tue Jan 11 01:06:33 CET 2005
On Mon, 10 Jan 2005 19:41:55 +0100, python at kareta.de wrote:
>Hi all,
>
>I am wondering about the following situation:
>
>I defined a class and inside this class I start a new thread with
>thread.start_new_thread. When I set some attributes of that class inside
>the thread_function, the attributes are not changed.
>
><code>
>class test:
> def __init__(self):
> self.param=''
> thread.start_new_thread(self.run_thread,())
> def run_thread(self):
> self.param='hello'
> return
>
>t=test()
>print t.param #result is an empty string
></code>
>The run_thread function operates on the same object but all changes are lost
>when the thread returns. How can I pass values from the thread function to the
>main thread ?
>
>
You are misdiagnosing the problem. The problem is that the __init__
function returns and your print statement executes before the run_thread
function has had a chance to run. Your main thread then exits,
self.param gets set, and the second thread exits.
That's the whole advantage of threads: they run independently.
If you really need to communicate like this, you'll need to use a Queue
or some other kind of interlock. However, if you DO find yourself
waiting like this very often, then it is quite likely that threads are
not the right answer for your problem.
--
- Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.
More information about the Python-win32
mailing list