'Stop main thread execution immediately if any of the other threads observes an exception in Python

I am trying to have a background thread/process to do some health checks on the system. and the main thread will be performing some other operations.

I want the main thread to stop/fail immediately if the background thread encounters any exceptions. Most of the solutions I could find online were using a while loop to check if the background thread is_alive(). But that won't fit in this scenario.

Can anyone help out with this?



Solution 1:[1]

Something I did with my threads is I had a global variable called "runThreads" or something similar, and I constantly have my threads each check if the value is true. If its false, the thread stops the loop and closes.

def DoSockets():
    return RunSockets

def DisableSockets():
    global RunSockets
    RunSockets = False

def ManageGameSockets():
    global MaximumPlayers
    global TotalPeople
    global ConnectedPeople
    global Users

    ConnectedPeople = len(Users)-1

    while True:
        if DoSockets():  # here it checks whether the threads should run or not every time the code loops
            print("Waiting for socket connections")
            TotalPeople += 1
            s.listen(99)
            time.sleep(1)
            if DoSockets():
                try:
                    conn, addr = s.accept()
                    print(f"{conn} has connected")
                    Thread(target=ManageSingleSocket, args=(conn, addr))
                    ConnectedPeople += 1
                    TotalPeople += 1
                except OSError:
                    pass
        else:
            break  # if it shouldn't run then break the loop
    print()
    "Stopping socket hosting"  # this is the last line and consequently should close the function/thread when it finishes 

assuming that is how threads work. I also just read that sys.exit() can close a specific thread. Read the answer from this: https://stackoverflow.com/questions/4541190/how-to-close-a-thread-from-within#:~:text=If%20sys.,will%20close%20that%20thread%20only.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 KingTasaz