[Tutor] stopping threads?

John Fouhy john at fouhy.net
Thu Sep 29 08:18:19 CEST 2005


On 29/09/05, Marcus Goldfish <magoldfish at gmail.com> wrote:
> I'm a little confused about threading in Python.  Here is a sample class
> I've written for monitoring for events.  Included in the comments are a
> couple of questions, specifically:

Hi Marcus,

>    (1) can I use super() in the constructor, or is direct call to base class
> preferred?

You can use super() --- in fact, there are some circumstances where it
is prefered: if you have complicated inheritance, super() will do a
better job. Check out this article for details:
http://python.org/2.2.3/descrintro.html

>    (2) do I need to sleep in the run() method?  If so, why?  It seems to
> improve my programs responsiveness

Without a sleep(), you are doing what is called "busy waiting". 
Remember, you only have one processor which is only capable of doing
one thing at once.  Without a sleep() call, your program runs
something like this:

#################
check self.undetected
  True
check self.undetected
  True
check self.undetected
  True
check self.undetected
  True
check self.undetected
  True
check self.undetected
  True
check self.undetected
  True
check self.undetected
  True
----- context switch
do something else
run the user interface
----- context switch
check self.undetected
  True
check self.undetected
  True
check self.undetected
  True
check self.undetected
  True
...etc.
#################

But when a thread sleeps, python knows that it can do a context switch
immediately, because the thread isn't going to be using the processor.

#################
check self.undetected
 True
sleep
----- context switch
do something else
run the user interface
----- context switch
check self.undetected
 True
sleep
----- context switch
do something else
run the user interface
----- context switch
...etc
#################

Does that help explain?

>    (3) what happens after run() finishes-- does the thread die, get
> suspended, go away?  Should I try to force the thread into one of these
> states, and if so how?

>From the docs:

#################
isAlive()
    Return whether the thread is alive.

    Roughly, a thread is alive from the moment the start() method
returns until its run() method terminates.
#################

If you keep a reference to the object, then it will die, but not go
away.  If you don't keep a reference, I imagine it will be garbage
collected once it dies. (I can't quote you docs for that, though)

There's no easy way to tell a thread to stop.  A common technique is
to make the thread check a boolean every time it goes through its
look.

eg:

#################
def __init__(self, *etc):
 self.die = False

def run(self):
 while not self.die:
  # do stuff

def stop(self):
 self.die = True
#################

HTH!

--
John.


More information about the Tutor mailing list