Owners need a second dict, from each owner to the starts it holds
The practice problem also frees every block one owner holds, in a single call. That needs a second dict.
P and R belong to job-1, and Q to job-2.
| State | Value |
|---|---|
blocks | {0: (3, "job-1"), 3: (5, "job-2"), 5: (8, "job-1")} |
owned | {"job-1": {0, 5}, "job-2": {3}} |
| free list | [(8, 10)] |
after free(5), which returns 3 | owned is {"job-1": {0}, "job-2": {3}} |
then release("job-1"), which returns 3 | it frees only the block at 0 |
The practice problem gives each block an owner, such as the job that asked for it. It adds release(owner), which frees everything that owner holds, the way a job's memory goes back when the job ends.
To find an owner's blocks without scanning them all, keep a second dict, owned, from each owner to the set of its blocks' starts. Store the owner next to the end: blocks[start] = (end, owner).
| State | Answers | Changes on alloc | Changes on free |
|---|---|---|---|
free_list | where the free runs are | split a run | merge with neighbours |
blocks, start to (end, owner) | is this a live block, how big, whose | add the start | remove the start |
owned, owner to a set of starts | which blocks an owner holds | add the start to its set | remove the start, and the owner once its set is empty |
The three must agree after every call. In the table, free(5) took 5 out of job-1's set, so the release that came after freed only the block at 0.
owned_from(blocks) builds the owned dict from the blocks dict in the table above. Write it, and leave out the blocks whose owner is None.