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 leastqtyare in stock, take them and returnTrue; otherwise change nothing and returnFalse.restock(item, qty): addqtyto 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.