복붙노트

[PYTHON] 일정 시간 후에 스레드를 중지하는 중

PYTHON

일정 시간 후에 스레드를 중지하는 중

일정 시간이 지난 후에 일부 스레드를 종료하려고합니다. 이 스레드는 무한 while 루프를 실행하며이 시간 동안 무작위로 많은 시간 동안 멈출 수 있습니다. 스레드는 duration 변수로 설정된 시간보다 오래 지속될 수 없습니다. 길이에 따라 설정된 길이 후에 스레드를 멈추게하려면 어떻게해야합니까?

def main():
    t1 = threading.Thread(target=thread1, args=1)
    t2 = threading.Thread(target=thread2, args=2)

    time.sleep(duration)
    #the threads must be terminated after this sleep

해결법

  1. ==============================

    1.차단하지 않으면 작동합니다.

    차단하지 않으면 작동합니다.

    당신이자는 것을 계획하고 있다면, 절대로 잠을 자도록 이벤트를 사용하는 것이 절대적으로 필요합니다. 이벤트를 활용하여 잠을 자면, 누군가가 "잠자는 동안"멈추라 고 말하면 깨울 것입니다. time.sleep ()을 사용하면 스레드가 깨어 난 후에 만 ​​스레드가 멈 춥니 다.

    import threading
    import time
    
    duration = 2
    
    def main():
        t1_stop = threading.Event()
        t1 = threading.Thread(target=thread1, args=(1, t1_stop))
    
        t2_stop = threading.Event()
        t2 = threading.Thread(target=thread2, args=(2, t2_stop))
    
        time.sleep(duration)
        # stops thread t2
        t2_stop.set()
    
    def thread1(arg1, stop_event):
        while not stop_event.is_set():
            stop_event.wait(timeout=5)
    
    def thread2(arg1, stop_event):
        while not stop_event.is_set():
            stop_event.wait(timeout=5)
    
  2. ==============================

    2.프로그램이 종료 될 때 (예를 들어 암시하는 것처럼) 스레드가 멈추게하려면 데몬 스레드로 만듭니다.

    프로그램이 종료 될 때 (예를 들어 암시하는 것처럼) 스레드가 멈추게하려면 데몬 스레드로 만듭니다.

    명령에 따라 스레드를 죽이려면 수동으로해야합니다. 다양한 방법이 있지만 스레드 루프에서 검사를 수행하여 종료 할 시간이 있는지 확인해야합니다 (Nix의 예 참조).

  3. from https://stackoverflow.com/questions/6524459/stopping-a-thread-after-a-certain-amount-of-time by cc-by-sa and MIT license