[python] 파이썬에서의 스레드 종료 방법
플래그를 활용할 때, 스레드는 정기적으로 플래그를 확인하고, 플래그가 설정되면 종료됩니다.
아래는 간단한 예제 코드입니다.
import threading
class MyThread(threading.Thread):
def __init__(self):
super(MyThread, self).__init__()
self.running = True
def run(self):
while self.running:
# 스레드가 수행해야 할 작업을 여기에 추가
pass
def stop(self):
self.running = False
# 스레드 시작
thread = MyThread()
thread.start()
# 스레드 종료
thread.stop()
위 코드 예제에서 MyThread
클래스는 running
플래그를 사용하여 스레드를 종료합니다. stop
메소드를 호출함으로써 running
플래그가 False
로 설정되어 스레드가 종료됩니다.
이 외에도 threading.Event
를 사용하는 방법이나 Thread.terminate()
를 사용하는 방법 등이 있으나, 이러한 방법은 예상치 못한 결과를 가져올 수 있으므로 권장되지 않습니다.
자세한 내용은 공식 파이썬 문서를 참고하시기 바랍니다.