The free list is [(0, 20)]: units 20 to 29 are in no block and no run.
Each call reads the free list and then changes it, and another thread can change it in between. The table shows one order of steps that loses units.
Here are four threads on the practice problem's worked solution, with an arena of 1,000,000 units. Each thread ran 5,000 rounds. Each round allocated 1 to 50 units, and freed the thread's oldest block once it held more than 20. sys.setswitchinterval(1e-6) made the threads switch often, so the race showed up in a short run.
- In three runs without a lock, calls raised
IndexError 13, 44 and 32 times. The free runs and live blocks together held 593, 1,882 and 1,429 units fewer than the arena: units that belonged to nothing.
- With one
threading.Lock held around alloc and free, three runs raised nothing, and every unit was accounted for.
import threading
class LockedAllocator(Allocator):
def __init__(self, size):
super().__init__(size)
self._lock = threading.Lock()
def alloc(self, n, owner=None, align=1):
with self._lock:
return super().alloc(n, owner, align)
def free(self, addr):
with self._lock:
return super().free(addr)
release and resize need the same with self._lock:. If a locked method calls another locked one, as release calls free, make the lock re-entrant: a threading.RLock.
One lock makes every call wait for every other. glibc's answer is more arenas: "The presence of multiple arenas allows multiple threads to allocate memory simultaneously in separate arenas, thus improving performance." The same idea in your design is an arena per worker, each with its own free list and its own lock.
units_lost(size, free_list, blocks) is the accounting check behind the numbers above: every unit must be free or in a live block. Write it, and the race in the table loses 10 units.