0

I was looking through online sites about anything about daeomon threads, but the best I could find was on the python documentation here. It only says that a thread that is flagged as a "daemon thread" will automatically kill itself when the main thread has shut down. It doesn't mention what would happen if these child processes died on their own, possibly due to an error.

To connect this with a project I'm currently working on, I'm working on an error checking process, where whenever a child thread that is running in the background finds an error, it shuts itself down and automatically restarts the entire IDE. I was wondering if daemon threads could automatically shut down the main thread, by simply shutting down their own.

…and if they cannot, are there any alternatives to this problem?

martineau
  • 119,623
  • 25
  • 170
  • 301
noobie
  • 57
  • 2
  • 9
  • 1
    "I was wondering if daemon threads could automatically shut down the main thread, by simply shutting down their own" - no. Why would you think that? – user2357112 Feb 07 '22 at 22:49
  • I'm not sure, that is why I asked. I'm somewhat new to this kind of threading concept and I was wondering if it could, since it would be a bit more convenient for me. – noobie Feb 07 '22 at 22:52
  • 1
    That's precisely what daemon threads **don't** do — see [my answer](https://stackoverflow.com/questions/38804988/what-does-sys-exit-really-do-with-multiple-threads/38805873#38805873) to another question about threading. – martineau Feb 07 '22 at 23:16
  • Is there a different type of thread that can do as I need? – noobie Feb 07 '22 at 23:30
  • Please clarify: You want to know a way for a (daemon?) thread to terminate the main thread (or what?) – martineau Feb 07 '22 at 23:48
  • Yes please, I'm wondering if I can shut down the main thread through a daemon thread – noobie Feb 08 '22 at 02:15

1 Answers1

0

You shouldn't kill a thread in Python, but you can ask it to stop what it is doing :

import time
import threading


MAIN_THREAD_SHOULD_STOP = False


def wait_5_seconds_then_ask_the_main_thread_to_stop():
    for i in range(5, 0, -1):
        print(i)
        time.sleep(1)
    print("asking to stop")
    global MAIN_THREAD_SHOULD_STOP
    MAIN_THREAD_SHOULD_STOP = True
    if not threading.currentThread().daemon:
        return


def doing_busy_work_until_asked_to_stop():
    while not MAIN_THREAD_SHOULD_STOP:
        print("busy busy busy")
        time.sleep(0.6)
    print("stopped")


if __name__ == "__main__":
    annex = threading.Thread(target=wait_5_seconds_then_ask_the_main_thread_to_stop, args=(), daemon=True)
    annex.start()
    doing_busy_work_until_asked_to_stop()
5
busy busy busy
busy busy busy
4
busy busy busy
busy busy busy
3
busy busy busy
2
busy busy busy
busy busy busy
1
busy busy busy
busy busy busy
asking to stop
stopped
Lenormju
  • 4,078
  • 2
  • 8
  • 22