Created
February 6, 2024 12:06
-
-
Save secemp9/ab9b0f2b7dbfb22dcd35700855a99d62 to your computer and use it in GitHub Desktop.
Threading wait POC 2
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 | |
| import signal | |
| 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() | |
| signal.signal(signal.SIGINT, self.handle_ctrl_c) | |
| try: | |
| with self.condition: | |
| while not self.shutdown: | |
| self.condition.wait() # Wait indefinitely for a shutdown signal | |
| except KeyboardInterrupt: | |
| pass # Handle first Ctrl+C | |
| 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 | |
| def handle_ctrl_c(self, signum, frame): | |
| print("Shutdown signal received, shutting down gracefully...") | |
| self.signal_shutdown() | |
| signal.signal(signal.SIGINT, signal.SIG_IGN) # Ignore further SIGINT signals | |
| 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