Why won't my thread terminate?

Steve Holden sholden at holdenweb.com
Thu May 22 16:51:29 EDT 2003


"Dfenestr8" <dfenestr8 at yahoo.com> wrote ...
> Hello.
>
> I read that a thread terminates when its run() method finishes.
>
> I'm trying to terminate  the thread below by changing the value upon which
a
> while loop runs to 0.
>
> But every time I try and get the thread running again, using the start()
> method, I get:
>
> "AssertionError: thread already started"
>
> What am I doing wrong?
>
> Here is the code for my thread......
>
>
> class metroThread(threading.Thread):
>         def __init__ (self):
>                 threading.Thread.__init__(self)
>                 self.cond = 1
>                 self.bpm = float(60)/100
>
>         def run(self):
>                 while self.cond == 1:
>                         self.mysound = tkSnack.Sound()
>                         self.mysound.read('mm.wav')
>                         self.mysound.play()
>                         sleep(self.bpm)
>
>         def stop(self):
>                 self.cond = 0
>                 #this sets the condition for the run()
>                 #method to terminate naturally.
>                 #no need to be messy about destroying the thread.
>
>         def play(self):
>                 self.cond = 1
>
>         def setBPM(self, bpm):
>                 self.bpm = float(60)/bpm
>
Repeat after me "The computer is a TOMCAT*". It's doing exactly what you
told it to: when you set the metroThread instance's cond attribute to zero
in the stop() method the loop inside the run() method ends, the method
returns and the thread terminates. Once a thread has terminated, that's it.

You seem to assume that a threading.Thread [subclass] instance can be
started as many times as you like. Unfortunately that isn't so. The
complaint you are seeing is Python telling you exactly that. Almost the only
documentation for the start() method says "This must be called at most once
per thread object".

Your answer is therefore to create a new instance each time you want to
re-invoke the thread's behavior.

regards
 Steve

* Thoroughly obedient moron: cannot actually think
--
Steve Holden                                  http://www.holdenweb.com/
Python Web Programming                 http://pydish.holdenweb.com/pwp/







More information about the Python-list mailing list