0

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?

NewMember
  • 21
  • 1
  • I think this will solve your problem https://stackoverflow.com/questions/73051054/python-threading-how-to-interrupt-the-main-thread-and-make-it-do-something-else/73067727#73067727 – Veysel Olgun Jul 28 '22 at 00:34

1 Answers1

0

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.

KingTasaz
  • 161
  • 7