repeat something in a thread, but stop when the program stops

Tim Peters tim.peters at gmail.com
Mon Sep 27 18:06:31 CEST 2004


[Harald Armin Massa]
> I need to do some synchronisations like in a cron.job
>
> import time
> from threading import Thread
>
> class updater(Thread):
>    def run(self):
>        while True:
>             do_updates()
>             time.sleep(600)
>
> updater().start()
>
> # regular program flow continues ....
> print "tralalala"
> while True:
>    do_very_important_stuff()
>    if ask_user_if_I_should_stop():
>        break
> 
> print "programm stopped because YOU decided ..."
> 
> #################################
> BUT ... the updater() thread keeps running. The software will not end
> until forced with keyboard interrupt.

It keeps running because you didn't mark your thread as a daemon
thread.  By default, Python waits for all threads to complete before
it will exit.  If you don't want Python to wait for some particular
thread T, do T.setDaemon(True) before starting T.  You have to accept
that T will then get killed ungracefully by your operating system when
Python exits (on most platforms).

Peter Otten suggested Queue.get() with a timeout, and that can also be
used.  If you do that, the thread will wake up about 20 times per
second to check the queue.  The logic here is better suited to a
Threading.Event, though (Queue is overkill; Event.wait() can also be
given a timeout).

...

> BUT... just to look at that queue the thread has to be activated. And
> ... the usual run-time of the software will be around 10hours, the
> update has to be done 20 times. And only in the evening the programm
> will be ended (shutdown of the computer). And more over: it will be in
> the background. time.sleep() takes essentially no processor time.
>
> Checking the queue will not stop the computer, but takes mor than
> necessary.

Measure it:  you won't be able to see a difference.  Modern processors
cram on the order of 1E9 cycles into each second.  Doing a tiny amount
of work 20 times per second is trivial.



More information about the Python-list mailing list