15/34
Part 4 of 7 · Live blocks and ownersLearn and do

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.

Blocks and their owners
0123456789
memory
PPPQQRRR

P and R belong to job-1, and Q to job-2.

StateValue
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 3owned is {"job-1": {0}, "job-2": {3}}
then release("job-1"), which returns 3it 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).

StateAnswersChanges on allocChanges on free
free_listwhere the free runs aresplit a runmerge with neighbours
blocks, start to (end, owner)is this a live block, how big, whoseadd the startremove the start
owned, owner to a set of startswhich blocks an owner holdsadd the start to its setremove 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.