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

后端 未结 2 1457
离开以前
离开以前 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条回答
  • 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)
    
    0 讨论(0)
  • 2021-02-20 19:24

    You can use _thread.interrupt_main (this module is called thread in Python 2.7):

    import time, threading, _thread
    
    def long_running():
        while True:
            print('Hello')
    
    def stopper(sec):
        time.sleep(sec)
        print('Exiting...')
        _thread.interrupt_main()
    
    threading.Thread(target = stopper, args = (2, )).start()
    
    long_running()
    
    0 讨论(0)
提交回复
热议问题