Cannot kill Python script with Ctrl-C

前端 未结 4 970
醉酒成梦
醉酒成梦 2020-11-27 10:56

I am testing Python threading with the following script:

import threading

class FirstThread (threading.Thread):
    def run (self):
        while True:
             


        
4条回答
  •  暖寄归人
    2020-11-27 11:43

    An improved version of @Thomas K's answer:

    • Defining an assistant function is_any_thread_alive() according to this gist, which can terminates the main() automatically.

    Example codes:

    import threading
    
    def job1():
        ...
    
    def job2():
        ...
    
    def is_any_thread_alive(threads):
        return True in [t.is_alive() for t in threads]
    
    if __name__ == "__main__":
        ...
        t1 = threading.Thread(target=job1,daemon=True)
        t2 = threading.Thread(target=job2,daemon=True)
        t1.start()
        t2.start()
    
        while is_any_thread_alive([t1,t2]):
            time.sleep(0)
    

提交回复
热议问题