python - 在Python中控制线程

标签 python multithreading python-2.7 python-multithreading

我们正在开发一个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

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

任何想法或建议都将受到高度赞赏。

提前致谢;

安德。

最佳答案

您应该处理线程内部的异常,而不是尝试重新启动它。您可以查看文档: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()

关于python - 在Python中控制线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52242966/

相关文章:

python - 如果行中的任何值等于零,则在 pandas 数据框中删除行

multithreading - 多线程应用程序实际上会比单线程应用程序更快吗?

c++ - 如果有 std::thread,Visual Studio 2017 linux 无法编译

java - 在决定使用 volatile 时,实际的锁是否重要?

python-2.7 - 使用 GTK 出错

python - 我怎样才能用 python sub 删除 <p> </p>

python - 导入错误: DLL load failed in Jupyter notebook but working in . py文件

Python 列出不同类型的成员资格

python - 如何将 numpy rearray 的子集转换为连续数组?

python - 如果我不使用集合,如何检查一个列表中的值是否在另一个列表中,并在 Python 中使用 if 语句的一行?