stoppable child thread

J

james_w77

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()
 
G

Gabriel Genellina

(e-mail address removed) ha escrito:
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'

Put a print statement just at the end of main() and see what happens.
You said:
What I want to do is to start 5 child threads, then do something, then
when got ^C keyboard exception, stop the child thread.

You've created the threads, you've handled ^C, what's missing...?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,143
Latest member
SterlingLa
Top