-1

In simplest case, I get infinite loop that works in separated thread:

while True:
   # Do

Sometimes I need to stop this loop by condition for some period of time. Then to start again. This mechanism should work automatically.

Which approaches are exist for that?

2
  • 1
    inside loop use variables like paused = False to control it. Commented Dec 9, 2017 at 20:22
  • Place a lock at the beginning of the loop. Simply acquire and release the lock. To stop the loop, acquire the lock from another thread. Commented Dec 9, 2017 at 23:46

1 Answer 1

1

One way to achieve this is to run the while loop on a different thread and have it keep track of the variable on the main thread. However it is necessary to kill the while thread when you wish to end the program.

import time
import winsound
import threading

class Player():
    def __init__(self, **kwargs):
        # Shared Variable.
        self.alarm_status = True
        self.thread_kill = False

    def start_sound(self):
        while True and not self.thread_kill:
            # Do somthing only if flag is true
            if self.alarm_status == True:
                winsound.PlaySound("alarm.wav", winsound.SND_FILENAME)


    def stop_sound(self):
        # Update the variable to stop the sound
        self.alarm_status = False

    #Function to run your start_alarm on a different thread
    def start_thread(self):
        #Set Alarm_Status to true so that the thread plays the sound
        self.alarm_status = True
        t1 = threading.Thread(target=self.start_sound)
        t1.start()

    def run(self):
        while True:
            user_in = str(raw_input('q: to quit,p: to play,s: to Stop\n'))
            if user_in == "q":
                #Signal the thread to end. Else we ll be stuck in for infinite time.
                self.thread_kill = True
                break
            elif user_in == "p":
                self.start_thread()
            elif user_in == "s":
                self.stop_sound()
            else:
                print("Incorrect Key")

if __name__ == '__main__':
    Player().run()
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.