Is it possible to kill the parent thread from within a child thread in python?
You can use _thread.interrupt_main
(this module is called thread
in Python 2.7):
import time, threading, _threaddef 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()
If the parent thread is the root thread, you may want to try os._exit(0)
.
import osimport threadingimport timedef 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)
The cleanest way to do this is to have a queue that the parent thread checks on a regular basis. If the child wants to kill the parent, it sends a message (e.g. "DIE") to the queue. The parent checks the queue and if it sees the message it dies.
q = queue.Queue() bc = queue.Queue() # backchannel def worker(): while True: key = q.get() try: process_key(key) except ValueError as e: bc.put('DIE') q.task_done() # Start the threads for i in range(args.threads): threading.Thread(target=worker, daemon=True).start() for obj in object_farm(): q.put(obj) try: back = bc.get(block=False) except queue.Empty: pass else: print("Data received on backchannel:",back) if back=='DIE': raise RuntimeError("time to die")