[Tutor] stopping threads?

Pierre Barbier de Reuille pierre.barbier at cirad.fr
Thu Sep 29 08:27:42 CEST 2005

Hello Marcus,

Marcus Goldfish a écrit :
> 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:
>   (1) can I use super() in the constructor, or is direct call to base class
> preferred?

IMO, it is better to explicitely call the base class ... I think it is
more readable. But I don't know if there is any drawback for any solution...

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

Yes, you need to sleep ! What you're doing is called "polling", you have
an infinite loop watching some state. If you don't wait, you'll use your
processor 100% for ... nothing ! Global responsiveness will decrease as
your program will always ask the OS for run-time ! Now, if you sleep,
you will test the state once, let other threads/process run and watch
some other time... 0.1 sec is quite a long time for processes and so
short for us ;) So if you need human-time responsiveness, you definitely
need this sleep. However, you may consider other way of
blocking/watching like using events or semaphors. So that your thread
will be blocked until someone releases it by sending the event or
releasing the semaphor.

>  (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?

Yop ! after run() finishes, the thread dies. This is the normal way to
finish a thread ... just end its main function :)

>  Any help is appreciated!
> Thanks,
> Marcus
>   class Monitor(threading.Thread):
>  def __init__(self):
>  threading.Thread.__init__(self) # would super() also work here? which is
> preferred
>  self.undetected = True # presumably, when the event occurs it sets this
> attribute to False
>   def run(self):
>  print "looking for event"
>  while self.undetected is True:
>  time.sleep(0.1) # another minor point: why do I need to sleep here?
>  self.processEvent()
>  # what happens here-- does the thread die?
>   def processEvent(self):
>  print "yeah-- event detected"
> ------------------------------------------------------------------------
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

Pierre Barbier de Reuille

INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP
Botanique et Bio-informatique de l'Architecture des Plantes
TA40/PSII, Boulevard de la Lironde

tel   : (33) 4 67 61 65 77    fax   : (33) 4 67 61 56 68

More information about the Tutor mailing list