2013-01-12 64 views
12

想象一下以下类:为什么重新启动线程时需要重新创建实例?

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

我要重新启动的线程的情况下,它已经死了。这并不奏效。因为线程只能启动一次。第一个问题。为什么是这样?

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

回答

14

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

如果娱乐是一个问题,没有必要为继承threading.Thread类,只是通过一个目标参数主题的构造是这样的:

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

然后,你可以访问螺纹部件来控制你的线程执行,并根据需要重新创建它。不需要MyObj娱乐。

0

我相信,这与Thread类的实现方式有关。它包装了一个真正的操作系统线程,所以重启线程实际上会改变它的身份,这可能会让人困惑。

一种更好的方式来处理线程实际上是通过目标函数/可调用:

class Worker(object): 
    """ Implements the logic to be run in separate threads """ 
    def __call__(self): 
     # do useful stuff and change the state 

class Supervisor(): 
    def run(self, worker): 
     thr = None 
     while True: 
      if not thr or not thr.is_alive(): 
       thr = Thread(target=worker) 
       thr.daemon = True 
       thr.start() 
      thr.join(1) # give it some time 
相关问题