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 1
count_down() - Decrement the count by 1; wake up all waiting threads when count reaches 0
wait() - Block the current thread until count reaches zero
get_count() - Return current count (for debugging/testing)
Parallel Task Completion: Wait for all parallel downloads to finish before merging results
Service Initialization: Wait for all microservices to be ready before accepting traffic
Batch Processing: Wait for all items in a batch to be processed
Testing: Coordinate multiple test threads to start/finish together
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!") `
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!
Thread-safe: Multiple threads can call methods concurrently
When count reaches 0, all waiting threads should be notified and resume
Count should not go below 0
wait() should return immediately if count is already 0
Handle spurious wakeups correctly
Should the latch be reusable after count reaches 0?
What happens if count_down is called when count is already 0?
Do we need timeout support for wait()?
Should we support negative initial counts (raise an error)?