By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,096 Members | 1,568 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,096 IT Pros & Developers. It's quick & easy.

Threading

P: n/a
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
Share this Question
Share on Google+
4 Replies


P: n/a
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

P: n/a
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

P: n/a
Ooops, forgot this link to the recipe:
http://aspn.activestate.com/ASPN/Coo...n/Recipe/65448

Nov 2 '05 #4

P: n/a
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.