【问题标题】:Killing all threads and the process from a thread of the same process从同一进程的线程中杀死所有线程和进程
【发布时间】:2014-02-10 07:58:52
【问题描述】:

我有一个产生 2 种线程类的进程。一个线程负责消费一个job_queue(这个类的100个线程通常在运行)。第二个线程是一个杀死线程。我正在使用从线程 2 设置的 result_done 标志,问题是我的线程 1 等待 X 秒,然后检查是否设置了 result_done 标志。

def run(self):
    while True:
        try:
            val = self.job_queue.get(True,self.maxtimeout) 
        except:
            pass
        if self.result_done.isset():
            return

现在,如果 maxtimeout 设置为 500 秒,并且我从另一个线程设置了 result_done 标志,则该线程将在退出之前等待 500 秒(如果队列中没有数据)。

我想要实现的是,一旦从进程的任何线程设置了 result_done 事件,所有线程都会随着当前进程优雅地终止,正确终止 db、websocket、http 连接等。

我正在使用 python 多进程库来创建产生这些线程的进程。

更新:所有线程都是 daemon=True 线程。

【问题讨论】:

  • 如果你想让线程优雅地死掉而不中断,你需要让它们成为非守护线程。

标签: python multithreading thread-safety exit multiprocess


【解决方案1】:

为避免等待maxtimeout 时间,您可以使用Event.wait() method:

def run(self):
    while not self.result_done.is_set():
        try:
            val = self.job_queue.get_nowait()
        except Empty:
            if self.result_done.wait(1): # wait a second to avoid busy loop
                return 

如果在调用期间设置了事件,Event.wait(timeout) 无需等待完整的timeout 即可返回。

【讨论】:

    猜你喜欢
    • 2014-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-06
    • 1970-01-01
    相关资源
    最近更新 更多