Threading

Dave Brueck dave at pythonapocrypha.com
Wed Nov 2 14:55:55 EST 2005


Tuvas wrote:
> I am trying to write a thread that will execute a function every 2
> seconds until the program is close, in which case it will stop. I can
> write the program easy enough to execute the command every 2 seconds,
> the problem comes when I try to close the program. It won't close the
> thread. Any ideas as to what I can do? Thanks!
> 

The simplest thing to do is call setDaemon on the thread object:

t = threading.Thread(target=MyFunc, args=(1,2,3))
t.setDaemon(1)
t.start()

This doesn't really give your other thread a chance to shutdown cleanly though, 
so if you need to "guarantee" clean shutdown, then have your thread check some 
shared flag or have some other way to know when it needs to quit, and then have 
the main thread wait for it to terminate by calling Thread.join.

For example, if you have a work queue, you could decide on the convention that 
None means all the work is done:

import threading, Queue, time

def Work(q):
     while 1:
         work = q.get()
         if work is None:
             break
         print 'Working on', work
         time.sleep(1)
     print 'Worker is quitting now'

q = Queue.Queue() # this queue is shared with the worker thread

# Start up a worker
t = threading.Thread(target=Work, args=(q,))
t.start()

# Give it stuff to do
for i in range(5):
     q.put(i)

# signal end of work
q.put(None)

print 'Main thread waiting for worker to be done'
t.join() # returns once all the work is done
print 'All done'

-Dave



More information about the Python-list mailing list