Python 中的控制线程

Control threads in Python

我们正在开发一个 Python 2.7 程序,它有多个线程。我们还制作了一个线程来监督所有线程是否正确运行。它本质上就这么简单:

all_my_threads = [controlador, usb, telegram, watch, registro, pantalla, hilo1, auto, authentication]

while True:

  for thread in all_my_threads:

    if (thread.isAlive()):

        print (str(thread) + " is alived.")

    else:

        print (str(thread) + " is not alived.")
        print ("Stating " + str(thread) + " thread.")
        thread.start()

  time.sleep(15)

当所有线程都是 运行 时,我们得到:

Thread(Thread-1, started 1943008212) is alived.
Thread(Thread-2, started 1943008368) is alived.
Thread(Thread-3, started 1926231152) is alived.
Thread(Thread-4, started 1934619760) is alived.
Thread(Thread-5, started 1961882736) is alived.
Thread(Thread-6, started 1951396976) is alived.
Thread(Thread-7, started 1971758192) is alived.
Thread(Thread-9, started 1982223472) is alived.

问题是我们已经看到,当线程因任何原因中断时,我共享的这段代码会尝试重新启动该线程,但它会因以下错误而崩溃:

threads can only be started once

所以这段代码一定有问题...

非常感谢任何想法或建议。

提前致谢;

安德.

您应该在 Thread 内部处理异常,而不是尝试重新启动它。您可以查看文档:https://docs.python.org/2/tutorial/errors.html

这样做更简单,更像 pythonic。

事实上你不能重新启动一个线程,而且大多数平台都不支持它。

当一个线程完成时,它的栈是死的;它的 parent 将被标记或发出信号;一旦加入,其资源将被删除。要重新启动它,您需要重新创建所有内容。如果你创建一个新线程,哪个更容易。

您可以创建一个重新创建线程的子类:

class RestartThread(threading.Thread):
    def __init__(self, *args, **kwargs):
        self._args, self._kwargs = args, kwargs
        super().__init__(*args, **kwargs)
    def clone(self):
        return RestartThread(*args, **kwargs)

现在您可以克隆您的线程以防出现异常:

if not test_thread.is_alive():
    test_thread = test_thread.clone()