为什么在重新启动线程时需要重新创建实例? [英] Why does the instance need to be recreated when restarting a thread?

查看:64
本文介绍了为什么在重新启动线程时需要重新创建实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下以下课程:

Class Object(threading.Thread):
    # some initialisation blabla
    def run(self):
        while True:
            # do something
            sleep(1)

class Checker():
    def check_if_thread_is_alive(self):
        o = Object()
        o.start()

        while True:
            if not o.is_alive():
                o.start()

如果线程已死,我想重新启动线程.这是行不通的.因为线程只能启动一次.第一个问题.为什么会这样?

I want to restart the thread in case it is dead. This doens't work. Because the threads can only be started once. First question. Why is this?

据我所知,我必须重新创建Object的每个实例并调用start()再次启动线程.如果是复杂的Object,这不是很实际.我必须读取旧Object的当前值,创建一个新值,并使用旧值在新对象中设置参数.第二个问题:这能以更聪明,更轻松的方式完成吗?

For as far as I know I have to recreate each instance of Object and call start() to start the thread again. In case of complex Objects this is not very practical. I've to read the current values of the old Object, create a new one and set the parameters in the new object with the old values. Second question: Can this be done in a smarter, easier way?

推荐答案

以这种方式实现threading.Thread的原因是保持线程对象与操作系统线程之间的对应关系.在主要操作系统中,无法重新启动线程,但是您可以创建具有另一个线程ID的另一个线程 .

The reason why threading.Thread is implemented that way is to keep correspondence between a thread object and operating system's thread. In major OSs threads can not be restarted, but you may create another thread with another thread id.

如果重新创建是一个问题,则无需从threading.Thread继承您的类,只需将目标参数传递给Thread的构造函数,如下所示:

If recreation is a problem, there is no need to inherit your class from threading.Thread, just pass a target parameter to Thread's constructor like this:

class MyObj(object):
    def __init__(self):
        self.thread = threading.Thread(target=self.run)
    def run(self):
        ...

然后,您可以访问线程成员以控制您的线程执行,并根据需要重新创建它.不需要MyObj娱乐.

Then you may access thread member to control your thread execution, and recreate it as needed. No MyObj recreation is required.

这篇关于为什么在重新启动线程时需要重新创建实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆