【问题标题】:Control threads in PythonPython中的控制线程
【发布时间】:2019-02-14 00:18:54
【问题描述】:

我们正在开发一个具有多个线程的 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) 是存活的。
Thread(Thread-2, started 1943008368) 已存活。
Thread(Thread-3, started 1926231152) 已存活。
Thread(Thread-4, started 1934619760) 已存活。
Thread(Thread-5, started 1961882736) 已存活。
Thread(Thread-6, started 1951396976) 已存活。
Thread(Thread-7, started 1971758192) 已存活。
Thread(Thread-9, started 1982223472) 已存活。

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

线程只能启动一次

所以这段代码肯定有问题……

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

提前致谢;

安德。

【问题讨论】:

    标签: python multithreading python-2.7 python-multithreading


    【解决方案1】:

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

    这样做更简单,也更 Pythonic。

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

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

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

    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()
    

    【讨论】:

    • 谢谢,但你能帮我实现你的 RestartThread 类,我对类不是很熟悉,也不知道如何正确调用它们。所以我在做 my_thread.clone() 时出错了
    猜你喜欢
    • 2011-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-22
    • 2012-07-10
    • 1970-01-01
    • 2011-10-14
    • 1970-01-01
    相关资源
    最近更新 更多