python终止线程的方法有哪些
方法一:
class BlockingTestThread(Thread):
def __init__(self):
self._running_flag = False
self.stop = threading.Event()
Thread.__init__(self, target=self.test_method)
def test_method(self):
try:
while(not self.swait(1)):
self._running_flag = True
print 'Start wait'
self.swait(100)
print 'Done waiting'
finally:
self._running_flag = False
def terminate(self):
self.sset()
if __name__ == "__main__":
thread = BlockingTestThread()
thread.start()
time.sleep(2)
print 'Time sleep 2'
thread.terminate()
print "Joining thread"
thread.join()
print "Done Joining thread"
方法二:
class Example(object):
def __init__(self):
self.stop = threading.Event()
self.connection = Connection()
self.mythread = Thread(target=self.dowork)
self.mythread.start()
def dowork(self):
while(not self.sis_set()):
try:
blockingcall()
except CommunicationException:
pass
def terminate():
self.sset()
self.connection.close()
self.mythread.join()