AlgoViz

Design an inventory management system

medium 80 min

Count goods in several places, promise them to orders without ever promising too much, ship or let go, and explain every count.

Watch lesson4:28

Locks by line

When one lock is not enough

The point: keep one lock until a sum says otherwise. If you split it, take the pieces in one fixed order, and plan again after you have them.

Numbers first

Is one lock too slow?

Assumed orders a secondWork under the lockLock busyVerdict
5020 µs0.1%Keep it
2,00020 µs4%Keep it
2,000400 µs (50,000 lines walked)80%Fix the walk, not the lock
40,00020 µs80%Split, or ask if one process is right
The third row is the usual truth. reserve in the simple version looks at all lines to find one product. An index by product makes it short again.

Deadlock

Two orders, two products, two orders of taking

Each thread holds what the other needs. More on deadlocks.

The cure is an order. If everyone takes locks by name, from a to z, nobody can hold plum and wait for fig while another holds fig and waits for plum.

Code

Sorted locks, plan inside

Python
from contextlib import ExitStackfrom threading import Lock, Threadclass Shelf:    """All lines of one product, with the lock that guards them."""    def __init__(self, counts):        self.lock = Lock()        self.on_hand = dict(counts)        self.held = {place: 0 for place in counts}    def plan(self, qty):        picks = []        for place in sorted(self.on_hand):            part = min(qty, self.on_hand[place] - self.held[place])            if part > 0:                picks.append((place, part))                qty -= part        return picks if qty == 0 else Noneclass Store:    def __init__(self, shelves):        self.shelves = shelves                      # sku -> Shelf, fixed after start    def reserve(self, wanted):        with ExitStack() as stack:            for sku in sorted(wanted):              # the one order everybody uses                stack.enter_context(self.shelves[sku].lock)            plans = {}            for sku, qty in wanted.items():                plans[sku] = self.shelves[sku].plan(qty)                if plans[sku] is None:                    return None                     # nothing was changed            for sku, picks in plans.items():                for place, part in picks:                    self.shelves[sku].held[place] += part            return plansstore = Store({"plum": Shelf({"cellar": 300, "shed": 200}), "fig": Shelf({"cellar": 1000})})sold = []def buyer(wanted):    for _ in range(200):        if store.reserve(wanted):            sold.append(1)                          # append is atomic in CPythonjobs = [Thread(target=buyer, args=(w,)) for w in ({"plum": 1, "fig": 1}, {"fig": 1, "plum": 1}) * 2]for t in jobs: t.start()for t in jobs: t.join()assert len(sold) == 500 and sum(store.shelves["plum"].held.values()) == 500assert store.shelves["fig"].held["cellar"] == 500print("500 sold, no deadlock")
800 tries, 500 jars. The lock guards one product in all places, because a plan has to see all its places at once.
Edit and run it in your browser

Traps

What splitting takes away

Was free with one lockNow
A new productThe map of shelves needs its own guard, or products are fixed at start
Sweep all promisesOne promise at a time, with the locks of that promise
Two threads end one promiseThe status needs its own compare and change
Movement numbers without gapsA counter for each product, or an atomic one that allows any order
A stock report of one momentEach shelf is true, but not all at the same instant

Forty thousand orders a second want the same jar.

BreaksA finer lock
How
One lock for each line
Limit
It is one line. There is nothing to split.
Choose when
Not for one hot product.
WorksRefuse early
How
An atomic counter of available pieces is read before the lock. At zero, answer sold out without waiting.
Limit
The counter may be a little old, so the lock still decides.
Choose when
Most buyers come too late: the usual sale.
StrongGive each worker its own share
How
1,000 jars become 10 shares of 100. A worker sells from its share and refills from a common rest.
Limit
Near the end, jars sit in the wrong share. The last ones need a common step.
Choose when
Very hot items. Across machines this is the idea of sharded counters.