我使用下面的示例来安全地停止线程。但是,如果我不知道哪些线程正在运行,如何停止当前正在运行的所有线程呢?你知道吗
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
相关问题 更多 >
编程相关推荐