2011-10-18 97 views
7

如何更好地編寫以下類?例如,有兩個標誌is_alive和is_finished有一個很好的方式來滑動?在python3中停止線程

Monitor(threading.Thread): 
    def run(self): 
     resource = Resource("com1") 

     self.alive = True 
     self.is_finished = False 
     try: 
      while self.alive: 
       pass # use resource 
     finally: 
      resource.close() 
      self.is_finished = True  

    def stop(self): 
     self.alive = False 
     while not self.is_finished: 
      time.sleep(0.1) 

回答

8

就是這樣。不過,你不需要is_finished,因爲你可以使用join()方法:

Monitor(threading.Thread): 
    def run(self): 
     resource = Resource("com1") 

     self.alive = True 
     try: 
      while self.alive: 
       pass # use resource 
     finally: 
      resource.close() 

    def stop(self): 
     self.alive = False 
     self.join() 

如果你需要找到如果一個線程在運行,你可以打電話mythread.is_alive() - 你不需要設置此你自己。