首页 > 解决方案 > 带有“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

而其他工人继续正常工作。

标签: pythonmultithreadingpython-3.7

解决方案


推荐阅读