progress

~/problems / Locks / Lock (mutex)

Last croissants at the bakery

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

A bakery's online shop keeps stock in a slow external store: store.get(item) -> int (0 if unseen) and store.put(item, count).

Implement Shop(store), called by many customer threads at once:

  • buy(item, qty) -> bool: if at least qty are in stock, take them and return True; otherwise change nothing and return False.
  • restock(item, qty): add qty to the stock.
store = ...                  # 3 croissants, 0 baguettes
shop = Shop(store)
shop.buy("croissant", 2)     # True, 1 left
shop.buy("croissant", 2)     # False, still 1 left
shop.restock("baguette", 5)
shop.buy("baguette", 5)      # True, 0 left
# 10 threads each try buy("croissant", 1) on a stock of 4:
#   exactly 4 get True, 6 get False, the stock ends at 0 (never negative)

The trap is check-then-act: two customers both see "1 left" and both take it. The tests' store is slow enough to make that happen.

qty >= 1. Shops over different stores must not block each other. Don't sleep or busy-wait.

Show hint

hold one threading.Lock (from __init__) across the get, the comparison and the put, in both methods.

Topic: Lock (mutex). One thread in a critical section at a time.

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