2011-10-18 3 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

꽤 많이 있습니다. 당신이 join() 방법을 사용할 수 있기 때문에, 당신의 is_finished 필요하지 않습니다 : 당신이 스레드가 실행되고 있는지 찾을 필요가없는 경우

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()를 호출 할 수 있습니다 - 당신이 설정할 필요가 없습니다 당신 자신.