Created
February 6, 2024 12:06
-
-
Save secemp9/4fd20bfb3a01fbff2e28f4eff0635af3 to your computer and use it in GitHub Desktop.
Threading wait POC
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import threading | |
| import time | |
| class ControlledExecution: | |
| def __init__(self): | |
| self.lock = threading.Lock() | |
| self.condition = threading.Condition(self.lock) | |
| self.shutdown = False | |
| def worker(self): | |
| print("Worker started. Press Ctrl+C to stop.") | |
| for i in range(10): # Simulated task | |
| with self.lock: | |
| if self.shutdown: | |
| print("Worker stopping early.") | |
| break | |
| print(f"Processing item {i}...") | |
| time.sleep(2) # Simulate time-consuming task | |
| else: | |
| print("Worker finished processing all items.") | |
| def main_loop(self): | |
| thread = threading.Thread(target=self.worker) | |
| thread.start() | |
| try: | |
| with self.condition: | |
| while not self.shutdown: | |
| self.condition.wait() # Wait indefinitely for a shutdown signal | |
| except KeyboardInterrupt: | |
| self.signal_shutdown() | |
| thread.join() | |
| def signal_shutdown(self): | |
| with self.lock: | |
| self.shutdown = True | |
| with self.condition: | |
| self.condition.notify_all() # Notify any waiting threads to wake up | |
| if __name__ == "__main__": | |
| controlled_execution = ControlledExecution() | |
| controlled_execution.main_loop() | |
| print("Main program exited gracefully.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment