python - 如何检测Python线程是否被杀死?

标签 python multithreading python-multithreading

我有自己的Thread,名为TimeBasedLogThread。当 TimeBasedLogThread 由于主进程正在退出而被终止时,我想触发一个函数 my_function 。我想从这个对象内部完成它。可以这样做吗?

这是我当前的方法:

class TimeBasedBufferingHandler(MemoryHandler):
    # This is a logging-based handler that buffers logs to send
    # them as emails
    # the target of this handler is a SMTPHandler

    def __init__(self, capacity=10, flushLevel=logging.ERROR, target=None,
                 flushOnClose=True, timeout=60):
        MemoryHandler.__init__(self, capacity=capacity, flushLevel=flushLevel, 
                                     target=target, flushOnClose=flushOnClose)
        self.timeout = timeout  # in seconds (as time.time())

    def flush(self):
         # Send the emails that are younger than timeout, all together
         # in the same email

class TimeBasedLogThread(Thread):
    def __init__(self, handler, timeout=60):
        Thread.__init__(self)
        self.handler = handler
        self.timeout = timeout

    def run(self):
        while True:
            self.handler.flush()
            time.sleep(self.timeout)

    def my_function(self):
        print("my_function is being called")
        self.handler.flush()


def setup_thread():
    smtp_handler = SMTPHandler()
    new_thread = TimeBasedLogThread(smtp_handler, timeout=10)
    new_thread.start()

在我的主线程中,我有:

setup_thread()

logging.error("DEBUG_0")
time.sleep(5)
logging.error("DEBUG_1")
time.sleep(5)
logging.error("DEBUG_2")

time.sleep(5) 在其他线程超时前 5 秒释放主线程。因此,我收到前两封包含“DEBUG_0”和“DEBUG_1”的电子邮件,但没有收到最后一封“DEBUG_2”,因为主进程在超时结束之前退出。

我想链接类TimeBasedLogThread和函数my_function,该函数将在退出之前刷新(发送电子邮件)。我怎样才能做到这一点?我看了source code 线程,但我不明白我可以使用什么方法。

最佳答案

也将您的函数构建为线程。 (例如:AfterDeadThread)

这里有两个策略:

  • TimeBasedLogThread 在死亡前调用 AfterDeadThread
  • AfterDeadThread 检查 TimeBasedLogThread 是否还活着,如果不活着就会运行一些方法

关于python - 如何检测Python线程是否被杀死?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56774047/

相关文章:

python - 对 numpy 中整列的顺序进行排序

python - 保存 Keras 模型 - UserWarning : Layer XX was passed non-serializable keyword arguments

Python 内存泄漏 - 为什么会发生?

C: signal() 是进程级的吗?

c# - 如何使 .NET COM 对象成为单元线程?

python - 从本地机器上的 psycopg2 连接到 Docker 上的 PostgreSQL 数据库

java - 登录多线程应用程序

除非最后一条语句很慢,否则python函数无法返回

python - 如何在Python中同时运行两个while循环?

python - 无法在Python中同时运行线程