progress

~/problems / Coordination / Condition variable

Countdown latch

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

A latch lets threads wait until count events have happened, like "all 3 services have started".

Implement Latch(count):

  • count_down(): decrease the count by 1, never below 0.
  • wait(timeout=None) -> bool: block until the count is 0 and return True (at once if it already is), or return False if timeout seconds pass first.
  • get_count() -> int: the current count.

All waiting threads must wake when the count hits 0.

latch = Latch(2)
# thread A: latch.wait()        -> blocks
# thread B: latch.count_down()  -> count 1, A still blocked
# thread C: latch.count_down()  -> count 0, A returns True
latch.wait(timeout=0.1)         # True immediately: already 0

Latch(1).wait(timeout=0.05)     # False after ~0.05s: nobody counted down

count >= 0. Don't sleep or busy-wait.

Show hint

keep the count behind one threading.Condition: wait uses cond.wait_for(lambda: self.count == 0, timeout), and count_down calls notify_all().

Topic: Condition variable. wait_for(predicate) + notify_all; always include a termination case.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc