Вот решение вашей задачи. Т к я недавно разбирался в том как это работает, то у меня был похожий пример - я его только малость переделал. Работает под Linux.
#!/usr/bin/env python
# vim: sw=4 ts=4 expandtab ai
import time
import threading
import signal
class Trtest(threading.Thread):
def __init__(self,letter,flagstop):
self.letter = letter
self.flagstop = flagstop
super(Trtest, self).__init__()
def run(self):
while not self.flagstop.isSet():
print str(self), self.letter
time.sleep(1.0)
def join(self, timeout=1.0):
while self.isAlive():
super(Trtest, self).join(timeout)
def stop(self):
print "stopping", str(self)
self.flagstop.set()
fl1 = threading.Event()
fl2 = threading.Event()
t1 = Trtest('A',fl1)
t2 = Trtest('B',fl2)
signal.signal(signal.SIGUSR1, lambda *a: t1.stop())
signal.signal(signal.SIGUSR2, lambda *a: t2.stop())
t1.start()
t2.start()
t1.join()
t2.join()
Только с нажатием кнопок извиняйте. Сделал на сигналах. Вот результат работы -
alex@kubu-book:~/development/PYTHON_projects$ python ./threadtest2.py & sleep 5; kill -10 %1; sleep 5; kill -12 %1
[1] 3680
<Trtest(Thread-1, started -1220207760)> A
<Trtest(Thread-2, started -1228600464)> B
<Trtest(Thread-1, started -1220207760)> A
<Trtest(Thread-2, started -1228600464)> B
<Trtest(Thread-1, started -1220207760)> A
<Trtest(Thread-2, started -1228600464)> B
<Trtest(Thread-1, started -1220207760)> A
<Trtest(Thread-2, started -1228600464)> B
<Trtest(Thread-1, started -1220207760)> A
<Trtest(Thread-2, started -1228600464)> B
stopping <Trtest(Thread-1, started -1220207760)>
<Trtest(Thread-2, started -1228600464)> B
<Trtest(Thread-2, started -1228600464)> B
<Trtest(Thread-2, started -1228600464)> B
<Trtest(Thread-2, started -1228600464)> B
<Trtest(Thread-2, started -1228600464)> B
stopping <Trtest(Thread-2, started -1228600464)>
alex@kubu-book:~/development/PYTHON_projects$
Он запускается, через 5 секунд получает сигнал прибить поток 1, а еще через 5 и поток 2, после скрипт завершается.
Советую почитать вот эту тему -
http://www.python.su/forum/viewtopic.php?id=7817Именно в ней приведено решение, а также куча материала, который надо изучать.