[英]Safely stop all running threads in Python
我使用下面的示例安全地停止线程。 但是,如果我不知道确切在运行哪些线程,该如何停止所有正在运行的线程?
class exampleThread(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.name = name
def run(self):
try:
print('this thread is running')
sleep(10)
finally:
print('example thread ended')
def get_id(self):
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')
example = exampleThread('example')
example.start()
现在我的线程正在运行。 但是,如何在不知道它们是否正在运行且是否声明了example
情况下,同时杀死多个线程?
为了安全地杀死线程,让它监听信号,它可以是内部变量或队列
在这里,我们定义了一个名为“ kill()”的方法,如果您需要杀死线程,它将把变量“ running”设置为False。
import threading
from time import sleep
class exampleThread(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.name = name
self.running=True
def run(self):
try:
while self.running: # watch for incoming kill signal
print('this thread is running')
sleep(1)
finally:
print('example thread ended')
def kill(self): # self kill safely
self.running = False
def get_id(self):
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')
example = exampleThread('example')
example.start()
sleep(2)
# alive = example.isAlive()
example.kill()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.