2017-11-28 1 views
-1
import time 
import threading 

class Check(threading.Thread): 
    def __init__(self): 
     self.stopped = False 
     threading.Thread.__init__(self) 

    def run(self): 
     i = 0 
     while not self.stopped: 
      time.sleep(1) 
      i = i + 1 
      print(i) 
      if(i==5): 
       self.stopped = True 

inst = Check() 
inst.start() 
+0

코드를 올바르게 형식 지정해야 StackOverflow에 바로 나타납니다. 코드 블록을 선택하고 중괄호 ('{}) '를 클릭하면 올바르게 표시되도록 4 칸 씩 위로 스쿠 핑합니다. 수정 패널 아래의 미리보기를보고 최종 결과를 확인하십시오. – jszakmeister

+0

코드 만 질문하는 것은 환영하지 않습니다 ... [ask]를 읽어야합니다. –

답변

0

스레드를 중지하기위한 자체 메커니즘을 설정해야합니다. 파이썬에는 내장 된 방법이 없습니다. 이것은 사실 파이썬뿐만 아니라 많은 언어에서 공통적 인 문제입니다.

import time 
import threading 

class Check(threading.Thread): 
    def __init__(self): 
     threading.Thread.__init__(self) 
     # An event can be useful here, though a simple boolean works too since 
     # assignment is atomic in Python. 
     self.stop_event = threading.Event() 

    def run(self): 
     i = 0 
     while not self.stop_event.is_set(): 
      time.sleep(1) 
      i = i + 1 
      print(i) 
      if(i==5): 
       self.stopped = True 

    def stop(self): 
     # Tell the thread to stop... 
     self.stop_event.set() 
     # Wait for the thread to stop 
     self.join() 

inst = Check() 
inst.start() 

# Do stuff... 
time.sleep(1) 

inst.stop() 

# Thread has stopped, but the main thread is still running... 
print("I'm still here!") 

는 여기 스레드가 중지해야하는지 여부를 알리기 위해 이벤트를 사용합니다. stop 메소드를 추가하여 이벤트를 알린 다음 계속하기 전에 스레드가 처리를 마칠 때까지 기다립니다. 이것은 매우 단순하지만 잘하면 당신이 취할 수있는 종류의 전략에 대한 아이디어를 줄 것입니다. run() 메서드에서 오류가 발생했는지 여부 또는 메서드 run()의 몸체가 너무 오래 걸리는 등의 오류 상황을 처리하려는 경우 훨씬 더 복잡합니다.