|
| 1 | +import random |
| 2 | +import threading |
| 3 | +import time |
| 4 | + |
| 5 | + |
| 6 | +class ThreadRace: |
| 7 | + def __init__(self): |
| 8 | + # Variable to store the result |
| 9 | + self.result = None |
| 10 | + # Event to mark if the race is finished |
| 11 | + self.race_finished = threading.Event() |
| 12 | + # Lock to protect the result variable |
| 13 | + self.lock = threading.Lock() |
| 14 | + # Store thread objects for termination |
| 15 | + self.threads = {} |
| 16 | + # Stop flags for each thread |
| 17 | + self.stop_flags = {} |
| 18 | + |
| 19 | + def task1(self, stop_flag): |
| 20 | + """First task function, can be modified as needed""" |
| 21 | + # Simulate random work time |
| 22 | + sleep_time = random.uniform(0.1, 2.0) |
| 23 | + |
| 24 | + # Break the sleep into smaller chunks to check stop flag |
| 25 | + chunks = 20 |
| 26 | + chunk_time = sleep_time / chunks |
| 27 | + |
| 28 | + for _ in range(chunks): |
| 29 | + # Check if we should stop |
| 30 | + if stop_flag.is_set(): |
| 31 | + return None |
| 32 | + time.sleep(chunk_time) |
| 33 | + |
| 34 | + return f"Task 1 completed in: {sleep_time:.2f} seconds" |
| 35 | + |
| 36 | + def task2(self, stop_flag): |
| 37 | + """Second task function, can be modified as needed""" |
| 38 | + # Simulate random work time |
| 39 | + sleep_time = random.uniform(0.1, 2.0) |
| 40 | + |
| 41 | + # Break the sleep into smaller chunks to check stop flag |
| 42 | + chunks = 20 |
| 43 | + chunk_time = sleep_time / chunks |
| 44 | + |
| 45 | + for _ in range(chunks): |
| 46 | + # Check if we should stop |
| 47 | + if stop_flag.is_set(): |
| 48 | + return None |
| 49 | + time.sleep(chunk_time) |
| 50 | + |
| 51 | + return f"Task 2 completed in: {sleep_time:.2f} seconds" |
| 52 | + |
| 53 | + def worker(self, task_func, task_name): |
| 54 | + """Worker thread function""" |
| 55 | + # Create a stop flag for this task |
| 56 | + stop_flag = threading.Event() |
| 57 | + self.stop_flags[task_name] = stop_flag |
| 58 | + |
| 59 | + try: |
| 60 | + # Execute the task with stop flag |
| 61 | + result = task_func(stop_flag) |
| 62 | + |
| 63 | + # If the race is already finished or we were asked to stop, return immediately |
| 64 | + if self.race_finished.is_set() or stop_flag.is_set(): |
| 65 | + return None |
| 66 | + |
| 67 | + # Try to set the result (if no other thread has set it yet) |
| 68 | + with self.lock: |
| 69 | + if not self.race_finished.is_set(): |
| 70 | + self.result = (task_name, result) |
| 71 | + # Mark the race as finished |
| 72 | + self.race_finished.set() |
| 73 | + print(f"{task_name} won the race!") |
| 74 | + |
| 75 | + # Signal other threads to stop |
| 76 | + for name, flag in self.stop_flags.items(): |
| 77 | + if name != task_name: |
| 78 | + print(f"Signaling {name} to stop") |
| 79 | + flag.set() |
| 80 | + |
| 81 | + return self.result |
| 82 | + |
| 83 | + except Exception as e: |
| 84 | + print(f"{task_name} encountered an error: {e}") |
| 85 | + |
| 86 | + return None |
| 87 | + |
| 88 | + def run_race(self): |
| 89 | + """Start the competition and return the result of the fastest thread""" |
| 90 | + # Reset state |
| 91 | + self.race_finished.clear() |
| 92 | + self.result = None |
| 93 | + self.threads.clear() |
| 94 | + self.stop_flags.clear() |
| 95 | + |
| 96 | + # Create threads |
| 97 | + thread1 = threading.Thread(target=self.worker, args=(self.task1, "Thread 1")) |
| 98 | + thread2 = threading.Thread(target=self.worker, args=(self.task2, "Thread 2")) |
| 99 | + |
| 100 | + # Record thread objects for later joining |
| 101 | + self.threads["Thread 1"] = thread1 |
| 102 | + self.threads["Thread 2"] = thread2 |
| 103 | + |
| 104 | + # Start threads |
| 105 | + thread1.start() |
| 106 | + thread2.start() |
| 107 | + |
| 108 | + # Wait for any thread to complete |
| 109 | + while not self.race_finished.is_set(): |
| 110 | + time.sleep(0.01) # Small delay to avoid high CPU usage |
| 111 | + |
| 112 | + # If all threads have ended but no result is set, there's a problem |
| 113 | + if ( |
| 114 | + not thread1.is_alive() |
| 115 | + and not thread2.is_alive() |
| 116 | + and not self.race_finished.is_set() |
| 117 | + ): |
| 118 | + print("All threads have ended, but there's no winner") |
| 119 | + return None |
| 120 | + |
| 121 | + # Wait for all threads to end (with timeout to avoid infinite waiting) |
| 122 | + thread1.join(timeout=1.0) |
| 123 | + thread2.join(timeout=1.0) |
| 124 | + |
| 125 | + # Return the result |
| 126 | + return self.result |
| 127 | + |
| 128 | + |
| 129 | +# Usage example |
| 130 | +if __name__ == "__main__": |
| 131 | + race = ThreadRace() |
| 132 | + result = race.run_race() |
| 133 | + print(f"Winner: {result[0] if result else None}") |
| 134 | + print(f"Result: {result[1] if result else None}") |
0 commit comments