Thread-Safe Inventory Management
Data Structure DesignAuto-graded · 17 test casesLast updated
Simulate concurrent inventory purchases and sales ensuring atomic state updates, preventing negative inventory, and handling invalid operations cleanly.
You are tasked with building a thread-safe inventory tracker for a online store trading digital goods. The system tracks the available unit balance of a single item and supports two core actions:
buy(quantity): Replenishes the stock by addingquantityunits to the available balance. A purchase operation always succeeds. It returns the total updated stock count immediately following the replenishment.sell(quantity): Attempts to deductquantityunits from the stock.- If the available stock is greater than or equal to
quantity, the sale succeeds: deductquantityunits from stock and returnTrue. - If the stock is insufficient, the sale fails: leave the stock completely unchanged (no partial deductions) and return
False.
- If the available stock is greater than or equal to
Requirements
To operate correctly under multi-threaded execution:
- No overselling: The current available stock must never drop below $0$.
- No lost updates: Concurrent modifications must be properly synchronized so that every addition and every successful deduction is accurately reflected in the final count.
- Atomic check-and-modify: Checking stock availability and performing the deduction within a sale must occur as a single atomic operation without interleaving from other calls.
Write a function stock_inventory that processes a list of operations sequentially. Given an initial stock count and parallel sequences of operation names and integer arguments, execute each command and collect the returned results.
If an unsupported operation name (anything other than "buy" or "sell") is encountered, raise a ValueError.
Constraints
0 <= initial <= 10^91 <= quantity <= 10^9for every action argument1 <= operations.length <= 10^5arguments.length == operations.length, where each element is a single-element list[quantity]
Examples
Example 1
Input: stock_inventory(100, ['sell', 'sell', 'buy', 'sell', 'sell'], [[30], [80], [50], [120], [1]])
Output: [True, False, 120, True, False]
Example 2
Input: stock_inventory(0, ['buy', 'sell', 'sell'], [[1], [1], [1]])
Output: [1, True, False]
Hints
Hint 1
Consider what happens if two threads try to execute a sale simultaneously when stock is only sufficient for one. A simple condition check followed by subtraction is vulnerable to race conditions.
Hint 2
Even `buy` operations modify shared state (`shares += quantity` is a read-modify-write process), so additions must also be protected under the same locking mechanism.
Hint 3
To satisfy atomicity in Python, guard the state checks and modifications inside a synchronized critical section using a standard lock.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge in managing shared mutable state across threads is avoiding race conditions—specifically time-of-check to time-of-use (TOCTOU) races and lost updates.
- Atomic Check-then-Act: For a
"sell"operation, checking ifshares >= quantityand subsequently subtractingshares -= quantitymust happen as an indivisible action. If another thread alters the balance between the check and the reduction, overselling occurs. - Synchronized Updates: Operations like
shares += quantityinvolve reading the current count, calculating the new sum, and writing back the result. Without synchronization, concurrent additions can overwrite each other.
We resolve this by wrapping state reads and updates inside a critical section protected by a mutual exclusion lock (threading.Lock).
Algorithm
- Maintain
sharesstarting atinitial. - Initialize a
Lockobject. - Iterate through each paired operation and argument:
- Acquire the lock using a context manager (
with lock:). - If
"buy", incrementsharesbyquantityand append the new balance toresults. - If
"sell", check ifshares >= quantity. If so, decrementsharesbyquantityand recordTrue; otherwise, recordFalse. - If an unrecognized string is given, raise
ValueError.
- Acquire the lock using a context manager (
Complexity
- Time Complexity: $\mathcal{O}(N)$ where $N$ is the number of operations. Acquiring/releasing the lock and basic integer arithmetic run in $\mathcal{O}(1)$ time per operation.
- Space Complexity: $\mathcal{O}(N)$ to store and return the list of execution outputs.
Implementation
from threading import Lock
from typing import List, Union
def stock_inventory(initial: int, operations: List[str], arguments: List[List[int]]) -> List[Union[int, bool]]:
shares = initial
lock = Lock()
results = []
for operation, args in zip(operations, arguments):
quantity = args[0]
with lock:
if operation == "buy":
shares += quantity
results.append(shares)
elif operation == "sell":
if shares >= quantity:
shares -= quantity
results.append(True)
else:
results.append(False)
else:
raise ValueError(f"Unknown operation: {operation}")
return results