Practice/Netflix/Countdown Latch
CodingMust
Design and implement a thread-safe counter that allows multiple threads to wait until the counter reaches zero. This is a classic concurrency primitive similar to java.util.concurrent.CountDownLatch.
Implement a CountdownLatch class with the following methods:
__init__(count) - Initialize with a count (must be >= 0)count_up() - Increment the count by 1count_down() - Decrement the count by 1; wake up all waiting threads when count reaches 0wait() - Block the current thread until count reaches zeroget_count() - Return current count (for debugging/testing)Create a synchronization primitive that allows one or more threads to wait until a set of operations being performed in other threads completes.
` import threading import time
def worker(latch: CountdownLatch, worker_id: int): """Simulate a worker doing some task.""" print(f"Worker {worker_id} starting...") time.sleep(0.5) # Simulate work print(f"Worker {worker_id} done!") latch.count_down()
latch = CountdownLatch(3)
for i in range(3): t = threading.Thread(target=worker, args=(latch, i)) t.start()
print("Main thread waiting for workers...") latch.wait() print("All workers completed!") `
Expected output:
Main thread waiting for workers... Worker 0 starting... Worker 1 starting... Worker 2 starting... Worker 0 done! Worker 1 done! Worker 2 done! All workers completed!
wait() should return immediately if count is already 0