借鉴知乎上大神的做法。
在python的API里面并没有杀死线程的方法,要么你就调用pthread或者WinAPI,要么就利用daemon的特性:父线程退出时子线程就自动退出。
看API是怎么说的
A boolean value indicating whether this thread is a daemon thread (True) or not (False). This must be set before start() is called, otherwise RuntimeError is raised. Its initial value is inherited from the creating thread; the main thread is not a daemon thread and therefore all threads created in the main thread default to daemon = False.
The entire Python program exits when no alive non-daemon threads are left.
所以我们可以新建一个线程作为父线程,然后实际工作是在它的一个子线程里面做,父线程循环检测一个变量来决定是否退出。Talk is cheap
import threadingclass TestThread(threading.Thread):
def __init__(self, thread_num=0, timeout=1.0):
super(TestThread, self).__init__()
self.thread_num = thread_num
self.stopped = False
self.timeout = timeout
def run(self):
def target_func():
inp = raw_input("Thread %d: " % self.thread_num)
print('Thread %s input %s' % (self.thread_num, inp))
subthread = threading.Thread(target=target_func, args=())
subthread.setDaemon(True)
subthread.start()
while not self.stopped:
subthread.join(self.timeout)
print('Thread stopped')
def stop(self):
self.stopped = True
def isStopped(self):
return self.stoppedthread = TestThread()thread.start()import timeprint('Main thread Wainting')time.sleep(2)thread.stop()thread.join()