在项目中碰到个问题,关于python的线程结束,python的threading库中没有相关的kill函数去结束线程,找到一种办法,我们可以新建一个线程作为父线程,然后在父线程中在起一个子线程来干我们的工作,父线程通过循环检测一个变量来决定是否退出,从而通过父线程的退出来,将工作的子线程退出,直接上代码看看
#!/usr/bin/env python
# coding: utf-8
import threading
class 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))
while True:
pass
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.stopped
thread = TestThread()
thread.start()
import time
print('Main thread Wainting')
time.sleep(2)
thread.stop()
thread.join()
运行后的结果为: