1

I have a homepage calling a thread object, the object is making some measurements, but sometimes if something goes wrong I want the homepage to stop the thread.

I am doing something like this Is there any way to kill a Thread in Python?

but this post says

The thread should check the stop flag at regular intervals.

is there a smart way to do that?

My code is making some setup, then is has a loop for each place it has to measure, and in that loop there is another loop for each time it has to measure each place.

I have been doing something like this:

def run(self):
    if EXIT is False:
       SETUP
       for place in places:
           if EXIT is False:
               for measurement in measurements:
                   if EXIT is False:
                       measure()
                   else:
                       break
           else:
               self.stop()
    else:
       self.stop()

This is only code example, I want a more beautiful way to check the exit request, and not use all the if statements

Thank you

Community
  • 1
  • 1
Laplace
  • 252
  • 2
  • 10

1 Answers1

1

Isn't it enough to check only within the innermost loop; and then you can throw an exception instead of checking the flag at all upper levels. You can even wrap this all in a function:

def check_thread_exit():
    if EXIT:
        thread.exit()

thread.exit()

Raise the SystemExit exception. When not caught, this will cause the thread to exit silently.

Then your code will simply become

def run(self):
    # an optional try-except block to do cleanup at top level
    try:
        SETUP
        for place in places:
            for measurement in measurements:
                check_thread_exit()
                measure()
    except SystemExit:
        CLEANUP
        raise`