Is it possible to kill the parent thread from within a child thread in python?

后端 未结 2 1473
离开以前
离开以前 2021-02-20 18:50

I am using Python 3.5.2 on windows.

I would like to run a python script but guarantee that it will not take more than N seconds. If it does ta

2条回答
  •  闹比i
    闹比i (楼主)
    2021-02-20 19:22

    If the parent thread is the root thread, you may want to try os._exit(0).

    import os
    import threading
    import time
    
    def may_take_a_long_time(name, wait_time):
        print("{} started...".format(name))
        time.sleep(wait_time)
        print("{} finished!.".format(name))
    
    def kill():
        time.sleep(3)
        os._exit(0)
    
    kill_thread = threading.Thread(target=kill)
    kill_thread.start()
    
    may_take_a_long_time("A", 2)
    may_take_a_long_time("B", 2)
    may_take_a_long_time("C", 2)
    may_take_a_long_time("D", 2)
    

提交回复
热议问题