可以通过以下方式来终止线程:通过抛出异常来终止进程
通过一个终止标志来终止进程
使用traces来终止进程
使用多线程模型来终止进程
通过将进程设置为deamon来终止进程
使用隐藏属性_stop()
通过抛出异常来终止进程
# Python program raising
# exceptions in a python
# thread
import threading
import ctypes
import time
class thread_with_exception(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.name = name
def run(self):
# target function of the thread class
try:
while True:
print('running ' + self.name)
finally:
print('ended')
def get_id(self):
# returns id of the respective thread
if hasattr(self, '_thread_id'):
return self._thread_id
for id, thread in threading._active.items():
if thread is self:
return id
def raise_exception(self):
thread_id = self.get_id()
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id,
ctypes.py_object(SystemExit))
if res > 1:
ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, 0)
print('Exception raise failure')
t1 = thread_with_exception('Thread 1')
t1.start()
time.sleep(2)
t1.raise_exception()
t1.join()
运行以上程序,一旦raise_exception()被调用,run()函数将被终止。这是因为程序抛出异常,将不在try...finally...函数块中运行,run()函数即被终止。
2.通过一个终止标志来终止进程
# Python program showing
# how to kill threads
# using set/reset stop
# flag
import threading
import time
def run():
while True:
print('thread running