progress

~/problems / Coordination / Condition variable

Baggage carousel

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

easy ~15 min

Handlers put bags on an airport carousel and passengers wait for their own. Each bag has a string tag; several bags can share one (a family's three suitcases).

Implement Carousel():

  • unload(tag): put one bag with this tag on the belt.
  • claim(tag, timeout=None) -> bool: wait until a bag with this tag is on the belt, take one off and return True; with a timeout in seconds, give up after that long and return False.
  • on_belt() -> int: bags on the belt now.
c = Carousel()
# passenger A: c.claim("AMS-17")          -> waits
# passenger B: c.claim("LIS-02")          -> waits
c.unload("LIS-02")                        # B returns True, A keeps waiting
c.unload("AMS-17")                        # A returns True
c.claim("NRT-99", timeout=0.1)            # False after ~0.1s
c.unload("X"); c.unload("X"); c.on_belt() # 2

Each bag goes to one passenger: two waiting for one bag means one gets it, the other keeps waiting. Don't sleep or busy-wait.

Show hint

a Counter of tags behind one threading.Condition; claim takes a bag only if cond.wait_for(lambda: bags[tag] > 0, timeout) returned True. unload needs notify_all(): a single notify() may wake someone waiting for a different tag.

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

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