Q263FreeSystemVerilog
Make the allocator thread-safe
Interview prompt
Question
Protect allocator invariants when several SystemVerilog processes may allocate, deallocate, or inspect state concurrently.
Starting point
Question code
class LockedRangeAllocator;
task alloc_exclusive(
int unsigned size,
output int unsigned addr,
output bit success
);
task dealloc_exclusive(
int unsigned addr,
int unsigned size,
output bit success
);
task fragmentation_metrics_exclusive(
output longint unsigned total_free,
output int unsigned largest_block,
output real external_ratio
);
task compact_exclusive(
ref int unsigned relocated_addr[int unsigned]
);
endclassReviewed example
Trace one case
Input
process A calls alloc_exclusive(16, addr, ok) while process B calls dealloc_exclusive(0x1000,16,ok)Expected output
one complete operation runs before the other; observers see either whole pre-state or whole post-stateA single lock spans every metadata update and is released on success and failure, preventing partially coalesced state from escaping.
What to cover
Requirements
- Use one lock for every operation touching allocator state.
- Release the lock on every control path.
- Do not expose partially updated range or allocation metadata.
- Document that the wrapper blocks while another process owns the lock.

