stoppable child thread
james_w77 at yahoo.com
james_w77 at yahoo.com
Fri Dec 22 15:14:18 EST 2006
I am trying to use Peter's StoppableThread(threading.Thread).
What I want to do is to start 5 child threads, then do something, then
when got ^C keyboard exception, stop the child thread.
For some reason (apparently strange for me :) ), the child threads can
NOT be stopped.
See the enclosed code for more info,
Thanks and have a nice Xmas.
Jimmy
============
#!/usr/bin/env python
import threading, thread
from time import sleep, ctime
class StoppableThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self._running = True
def stop(self):
self._running = False
def run(self):
while self._running:
# do stuff here that loops periodically to allow
# the flag to be checked
print 'start loop at:', ctime()
sleep(4)
def main():
threads = []
try:
for i in range(5):
t = StoppableThread()
t.start()
sleep(0.001)
threads.append(t)
except KeyboardInterrupt:
for t in threads:
t.stop()
t.join()
del threads[:]
print 'child thread exiting...'+'/n/n'
if __name__ == '__main__':
main()
More information about the Python-list
mailing list