python - 带有“while True”和“catch all exceptions”的线程有时会死掉
问题描述
这是我的应用程序的简化版本。我运行了几天,然后其中一个线程死了(线程 D)。理论上不应该发生。因为它处于“while True”循环并处理所有异常。有任何想法吗?
import time
import logging
from threading import Thread
class Worker(Thread):
def __init__(self, name):
super().__init__()
self.name = name
def run(self):
logging.info(f"[self.name] Worker started")
while True:
try:
for work in work_list:
logging.info(f"[self.name] Doing the work...")
work.do_work()
time.sleep(self.sleep_time)
except CustomException as ex:
logging.warning("Exception")
time.sleep(self.sleep_time)
except:
logging.exception("Exception")
time.sleep(self.sleep_time)
def main():
workers = []
worker_names = ["A","B","C","D","E","F"]
for worker_name in worker_names:
worker = Worker(worker_name)
workers.start()
workers.append(worker)
while True:
for worker in workers:
if not worker.is_alive():
logging.error(f"Worker '{worker.name}' died")
worker.join(1)
if __name__ == '__main__':
main()
D工人的日志是这样的:
2021-07-21 08:36:42,121 INFO - [D] Worker started
2021-07-21 12:58:52,649 INFO - [D] Doing the work
2021-07-21 16:52:55,794 INFO - [D] Doing the work
Worker 'D' died
Worker 'D' died
Worker 'D' died
而其他工人继续正常工作。
解决方案
推荐阅读
- java - predic8 wsdl 解析器在读取 include xsd 语句后停止
- node.js - 实时数据库触发通知
- character-encoding - 使用 UTF8 字符集创建 Informix 实例
- php - Angular 视图作为 PHP
- sql-server - 将地理转换为wkt时sql中的STAsText()和ToString()有什么区别
- python - Cuda 错误消息:F ./tensorflow/core/util/cuda_launch_config.h:127] 检查失败:work_element_count > 0 (0 vs. 0)
- php - 如何使用数据库在codeigniter中上传多个图像
- php - 如何使用 PHP 将数组映射为键值?
- angular - Angular 4. 使用服务共享来自 API 响应的数据或保存在组件内
- c# - 使用 DotSpatial 重新投影 SRID