Python 线程悄无声息地崩溃并消失
我有一个线程每100毫秒执行一次轮询操作。 一段时间后,当应用程序继续运行时,线程显然无缘无故地消失了 线程没有被阻塞,因为如果我打印应用程序中存在的所有线程,轮询线程就不存在了 代码如下:Python 线程悄无声息地崩溃并消失,python,multithreading,raspberry-pi,Python,Multithreading,Raspberry Pi,我有一个线程每100毫秒执行一次轮询操作。 一段时间后,当应用程序继续运行时,线程显然无缘无故地消失了 线程没有被阻塞,因为如果我打印应用程序中存在的所有线程,轮询线程就不存在了 代码如下: def run(self): logger.info('PollThread thread started...') last_poll_time = curr_ms() / 1000 while not self._stop_event.isSet(): logg
def run(self):
logger.info('PollThread thread started...')
last_poll_time = curr_ms() / 1000
while not self._stop_event.isSet():
logger.debug('will do stuff')
# doing stuff
logger.debug('done!')
# sleep until next polling cycle
curr_time = curr_ms() / 1000
logger.debug('thread present 1')
time_from_last_poll = curr_time - last_poll_time
if IO_POLLING_PERIOD > time_from_last_poll:
sleep_period = IO_POLLING_PERIOD - time_from_last_poll
if sleep_period > IO_POLLING_PERIOD:
sleep_period = IO_POLLING_PERIOD
logger.debug('thread present 2')
logger.debug('thread present 2')
time.sleep(sleep_period)
logger.debug('thread present 3')
logger.debug('thread present 4')
last_poll_time = curr_ms() / 1000
logger.debug('thread present 5')
logger.info('terminated....')
curr\u ms()
的定义如下:
def curr_ms():
return int(round(time.time() * 1000))
IO轮询周期是:
IO_POLLING_PERIOD = 0.1
打印“螺纹存在1”后螺纹消失。
之后将不会打印任何消息
调试尤其困难,因为问题可能在运行的几天内发生一次。
在Raspberry Pi 1上运行的代码
已解决:由于日志字符串格式错误,线程正在崩溃。在我上面介绍的代码中,我删除了这一行以澄清代码结构。添加try/catch后,我能够找到问题。线程崩溃没有导致应用程序退出。您确定已定义IO轮询周期吗?如果您尝试在“thread present 1”行打印它会怎么样?在任何情况下,您都可以尝试将整个事件包装在try
块中,并使用except
记录发生的错误(因为肯定有错误发生)。@xzoert,IO轮询周期已定义,否则整个事件将无法工作。感谢您提出的关于try
/catch
的想法,我们将尝试;)