我想知道如何检查父线程是否仍然存在/卡住。基本上我有一个父线程向孩子发送命令。如果父线程死亡或遇到死锁条件,我不希望孩子继续生存。以下是迄今为止我实现的基本框架。
from Queue import Queue
from threading import Thread
class myClass:
def __init__(self):
self.currentCommand = Queue()
t = Thread(target=self._run)
t.start()
def close(self):
self._sendCommand("close")
def _run(self):
while True:
if self.currentCommand.empty():
pass
#do some task
else:
command = self.currentCommand.get()
if command == "close":
#clean up
self.currentCommand.task_done()
break
else:
#do command task
self.currentCommand.task_done()
def _sendCommand(self, command):
self.currentCommand.put(command)
self.currentCommand.join()
我的一个想法是定期从父母那里向孩子发送计算机时间。如果时间大于设定值,孩子就会死亡。有没有更简单或更有效的方法?同样在 python 文档中,线程类中有一个 isAlive 方法,但我不确定如何使用它。