468,287 Members | 2,010 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,287 developers. It's quick & easy.

Threading

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!

Nov 2 '05 #1
4 1477
How do you use threads? With threading.Thread objects? Then this recipe
might help, it did it for me. For further assistance please post your
code.

Nov 2 '05 #2
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
Nov 2 '05 #3
Ooops, forgot this link to the recipe:
http://aspn.activestate.com/ASPN/Coo...n/Recipe/65448

Nov 2 '05 #4
That helps alot with the Daemon and recipe! Thanks for the help!

Nov 2 '05 #5

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

65 posts views Thread by Anthony_Barker | last post: by
2 posts views Thread by Egor Bolonev | last post: by
6 posts views Thread by CK | last post: by
2 posts views Thread by Vjay77 | last post: by
11 posts views Thread by Paul Sijben | last post: by
reply views Thread by kingcrowbar.list | last post: by
7 posts views Thread by Mike P | last post: by
126 posts views Thread by Dann Corbit | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.