0

I have some code similar to what's below. I have SomeClass which starts a thread by calling MyThread. The thread runs in a loop, but there can be very long delays in the loop (I've set the example to 120secs here). How do I go about interrupting the loop even while it's "sleeping" or idle waiting for the next for iterator? I can call the stop_thr method, but this only stops the loop on the next iteration.

What's the best way to go about handling this?

class SomeClass
  def __init__():
    self.thr = MyThread()
    self.thr.start()

  def stop_thr():
    self.thr.stop_thr()


class MyThread(threading.Thread)
  def __init__(self, **kwargs)
    super().__init__(**kwargs)
    self.running = False

  def run():
    self.running = True
    while self.running:
      for x in range(1000):
        # do stuff
        sleep(120)   # How do I interrupt this if signaled without waiting the full time?

        if not self.running:
          break  # This works, but only after the 120secs elapses

  def stop_thr():
    self.running = False
trb
  • 120
  • 2
  • 12
  • "I can call the stop_thr method" - when called that should stop both of 2 loops – RomanPerekhrest Jan 23 '23 at 18:03
  • @RomanPerekhrest the issue is that OP wants the loop to stop promptly even if the thread is currently waiting for a long-running `sleep`. Simply setting the `.running` flag won't abort until the next time that flag is checked, which is after the blocking `sleep` call finishes. Fortunately, this is a well-known problem and I could easily find an existing duplicate of the question. – Karl Knechtel Jan 23 '23 at 18:08
  • What do you mean with "idle waiting for the next for iterator"? – Kelly Bundy Jan 23 '23 at 18:51
  • @KellyBundy Idle as in this case sleeping or waiting for a generator to yield the next event. – trb Jan 23 '23 at 18:55
  • Looks like you'll need to make that clearer in the question, perhaps with a more realistic example, if you still want an answer for such non-sleep waiting. – Kelly Bundy Jan 23 '23 at 19:04

0 Answers0