কম্পিউটার বিজ্ঞান · বই 5 · স্নাতক তৃতীয় বর্ষ

University Computer Science — Year 3

এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: English।

University Computer Science — Year 3 · স্নাতক তৃতীয় বর্ষ

9Memory Management and Garbage Collection

A C program asks for memory with malloc and gives it back with free; a Python, Java or Lisp program only asks, and something else decides when a block can be reused. This chapter opens both boxes. It writes the allocator behind malloc and measures how its free memory crumbles into pieces; it then writes the three classic ways of finding the blocks a program can no longer use (counting references, tracing from the roots, and copying), proves what each guarantees, and measures what each costs on a model of the town’s server. A last section asks what a language without a collector, such as Rust, pays instead.

You already know

The Year 1 volume’s heap is the region from which malloc hands out blocks while a program runs; free returns one. A block the program can no longer reach but never freed is a memory leak; a pointer used after its block was freed is dangling.

A magnetic-core memory plane: 32 by 32 ferrite rings at the crossings of the wires, each holding one bit, 1024 bits in all, or 128 bytes. Programs that build lists and trees as they run must reuse memory: a whole plane holds only eight of this chapter’s cells.
A magnetic-core memory plane: 32 by 32 ferrite rings at the crossings of the wires, each holding one bit, 1024 bits in all, or 128 bytes. Programs that build lists and trees as they run must reuse memory: a whole plane holds only eight of this chapter’s cells.

9.1 Allocators

Definition 9.1 (Allocator, free list, first fit, best fit, boundary tag)

An allocator manages a region of memory: it hands out blocks on request and takes them back. Its free list is the set of its free blocks, found by walking all the blocks in address order or linked through the free blocks themselves. Given a request, first fit takes the first free block large enough, in address order; best fit takes the smallest free block large enough. A boundary tag is a word at each end of a block that records its size and whether it is in use.

Listing 9.1 lays the arena out: the blocks tile it from one end to the other, so the size in a block’s header leads to the next block, and the footer at its end lets the block after it find the start of this one. A used word at each end of the arena, the prologue and the epilogue, saves every walk from testing the bounds.

/* arena.c -- every block, free or used, starts and ends with a boundary tag: its size in
   bytes, with the low bit set when the block is in use. The blocks tile the arena. */
#include "arena.h"

#define W sizeof(size_t)
#define N (ARENA_BYTES / W)
#define MIN_BLOCK 32
static size_t heap[N];
static arena_fit fit;

static size_t size(size_t i) { return heap[i] & ~(size_t)1; }
static int used(size_t i) { return heap[i] & 1; }
static size_t next(size_t i) { return i + size(i) / W; }
static void tag(size_t i, size_t bytes, size_t in_use)
{
    heap[i] = heap[i + bytes / W - 1] = bytes | in_use;  /* header and footer */
}
Listing 9.1. Boundary tags. Sizes are multiples of 16 bytes, so the lowest bit of a tag is free to say whether the block is in use. code/bachelor-3/09-garbage-collection/listings/arena.c
void arena_init(arena_fit policy)
{
    fit = policy;
    heap[0] = 1;             /* prologue: a footer in use, so nothing merges past the start */
    tag(1, (N - 2) * W, 0);  /* one free block, the whole arena */
    heap[N - 1] = 1;         /* epilogue: a header in use of size 0, where every walk stops */
}

size_t first_fit(size_t bytes)
{
    for (size_t i = 1; size(i) > 0; i = next(i))
        if (!used(i) && size(i) >= bytes) return i;
    return 0;
}

size_t best_fit(size_t bytes)
{
    size_t best = 0;
    for (size_t i = 1; size(i) > 0; i = next(i))
        if (!used(i) && size(i) >= bytes && (best == 0 || size(i) < size(best))) best = i;
    return best;
}
Listing 9.2. An empty arena, and the two placement policies, each a walk over the blocks. code/bachelor-3/09-garbage-collection/listings/arena.c

A request for nn bytes needs a block of nn plus two tags, rounded up to 16 bytes. If the chosen free block is larger, the allocator splits it and the tail stays free; if the tail would be too small to hold even its own tags and a little payload, the request takes the whole block (Listing 9.3).

Definition 9.2 (Fragmentation, coalescing of free blocks)

Internal fragmentation is memory inside used blocks that the program did not ask for: tags and rounding. External fragmentation is free memory split into blocks too small to serve a request, although their total would; we measure it as 1−largest free block/total free1 - \text{largest free block}/\text{total free}. Coalescing of free blocks merges a freed block with the free blocks next to it in memory, so that no two free blocks touch.

void *arena_alloc(size_t n)
{
    size_t bytes = arena_block_bytes(n), i = fit(bytes);
    if (i == 0) return NULL;
    size_t rest = size(i) - bytes;
    if (rest >= MIN_BLOCK) {  /* split: the tail stays free */
        tag(i, bytes, 1);
        tag(i + bytes / W, rest, 0);
    } else {
        tag(i, size(i), 1);   /* too small a tail: the request takes the whole block */
    }
    return &heap[i + 1];
}

void arena_free(void *p)
{
    size_t i = (size_t)((size_t *)p - heap) - 1, bytes = size(i);
    if (!used(next(i))) bytes += size(next(i));  /* coalesce with the next block */
    if (!used(i - 1)) {  /* and with the previous block, whose footer is at i - 1 */
        i -= size(i - 1) / W;
        bytes += size(i);
    }
    tag(i, bytes, 0);
}
Listing 9.3. Allocating with a split, and freeing with coalescing on both sides. The footer at i−1i - 1 gives the previous block’s size, so its start, in constant time. code/bachelor-3/09-garbage-collection/listings/arena.c
Freeing the middle block of 96 bytes. Its neighbours on both sides are free: the footer just before it gives the start of the block of 64, and its own size gives the header of the block of 128. The three become one block of 288 bytes; the grey boundary tags at its two ends are rewritten, the ones in between are simply forgotten.
Freeing the middle block of 96 bytes. Its neighbours on both sides are free: the footer just before it gives the start of the block of 64, and its own size gives the header of the block of 128. The three become one block of 288 bytes; the grey boundary tags at its two ends are rewritten, the ones in between are simply forgotten.

Which policy fragments less depends on the program. Output 9.1 runs one seeded workload of 20,000 steps under each: 280 slots, each either empty or holding a block, are allocated and freed at random, with mostly small requests and one in five a buffer of 400 to 2,000 bytes, in an arena of 64 KiB.

$ gcc -std=c17 -O2 -Wall -Wextra -o frag frag.c arena.c -lm && ./frag
first fit failed   17, with at least  6208 B free each time
          used 46368 B in 157 blocks (internal  7.8 %)
          free 19152 B in  32 blocks, largest 10016 B (external 47.7 %)
          free blocks by size: <64 17, <128 3, <256 1, <512 2, <1K 4, <2K 4, <4K 0, more 1
best fit  failed   11, with at least  9824 B free each time
          used 41008 B in 145 blocks (internal  8.3 %)
          free 24512 B in  22 blocks, largest  5472 B (external 77.7 %)
          free blocks by size: <64 4, <128 3, <256 5, <512 2, <1K 1, <2K 3, <4K 2, more 2
Output 9.1. One workload under first fit and best fit: the requests that found no free block large enough, and the arena at the end.

Best fit refused 11 requests and first fit 17, all of them buffers of at most 2,016 bytes, although each time at least 6,208 bytes were free: external fragmentation, not a lack of memory. First fit ends with 17 free blocks under 64 bytes, slivers too small for almost any request. Internal fragmentation is under 10 %, the price of the tags and the rounding. A real allocator keeps a separate free list per size class (segregated lists), so that a small request never searches the large blocks and blocks of one size sit together; for a request of a given class, its search is constant time.

9.2 Reference counting

From here on the program does not call free: the runtime must find out by itself when a block can never be used again.

Definition 9.3 (Reference counting)

Reference counting stores in each object its reference count, the number of references to it held by variables and by other objects. Every copy of a reference increments the count of its target, every overwritten or discarded reference decrements it, and an object whose count reaches 0 is freed at once, decrementing the counts of the objects it refers to.

CPython counts references. sys.getrefcount shows a count one higher than expected, because its own argument is a reference while it runs (Listing 9.4).

"""refcount.py -- CPython counts references; its cycle collector finds what
counting misses."""
import gc
import sys


class Loan:
    def __init__(self, title):
        self.title, self.other = title, None

    def __del__(self):
        print(f"  freed {self.title}")


a = Loan("Dune")
print("one name:        ", sys.getrefcount(a))  # one more: the argument itself
b = a
shelf = [a, a]
print("three more:      ", sys.getrefcount(a))
del b
shelf.clear()
print("back to one name:", sys.getrefcount(a))
print("del a:")
del a  # the count drops to zero: freed at once

gc.disable()  # no automatic cycle collection while we watch
x, y = Loan("Emma"), Loan("Ulysses")
x.other, y.other = y, x  # a cycle: each keeps the other's count at 1
print("del x, y:")
del x, y
print("  (nothing freed)")
print("gc.collect():")
print("  unreachable objects found:", gc.collect())
Listing 9.4. Counts rising and falling, an object freed the moment its count reaches 0, and a cycle that counting cannot free. code/bachelor-3/09-garbage-collection/listings/refcount.py
$ python refcount.py
one name:         2
three more:       5
back to one name: 2
del a:
  freed Dune
del x, y:
  (nothing freed)
gc.collect():
  freed Emma
  freed Ulysses
  unreachable objects found: 2
Output 9.2. Dune is freed by del a, before the next line runs. Emma and Ulysses survive their names: each keeps the other’s count at 1, until the cycle collector finds them unreachable.

The good side of counting is in the first half of the output: memory comes back at a known moment, in small steps, with no pause. The bad side is the second half: two objects that refer to each other keep their counts above 0 forever, whether the program can reach them or not. CPython therefore adds a tracing collector for cycles, the subject of the next section, and gc.collect reports the number of unreachable objects it found. Counting has two other costs: every assignment of a reference writes two counts, which is costly when several threads share objects, and freeing a long list frees its cells one after the other in one go. Deferred counting ignores the references held in local variables and checks for zero counts now and then; weighted counting splits a weight between copies of a reference so that copying it does not touch the target.

9.3 Tracing: mark and sweep

Definition 9.4 (Root set, reachable object, garbage)

The root set of a running program is the set of references it holds outside the heap: in its variables, its registers and its call stack. An object is reachable if a path of references leads to it from a root. A heap object that is not reachable is garbage: no future step of the program can read it.

Garbage is a safe approximation of “never used again”: an unreachable object is certainly never used, while a reachable one may or may not be. A collector frees only garbage, so it never frees an object the program will use.

The collectors of this chapter manage a heap of cells (heap.h), each with an integer and two references, which is enough for lists, trees and arbitrary graphs. Their program is a model of the town’s server (server.h): each request builds a list of short-lived work, then a session, a list of a few cells kept in a table of the most recent sessions, the roots. Every reference the program keeps across an allocation is in that table, since an allocation may collect.

Definition 9.5 (Garbage collection, mark and sweep, tri-colour invariant)

Garbage collection is the automatic freeing of garbage. A mark-and-sweep collector marks every object reachable from the roots, then sweeps the whole heap and frees every object left unmarked. During marking, an object is white if not yet reached, grey if reached but its references not yet examined, black if reached and all its references examined. The tri-colour invariant says that no black object refers to a white one.

static void mark(void)
{
    int top = 0;
    for (int r = 0; r < nroots; r++)
        if (roots[r] != NIL && heap[roots[r]].meta == WHITE) {
            heap[roots[r]].meta = MARKED;  /* grey: marked, on the stack */
            stack[top++] = roots[r];
        }
    while (top > 0) {
        int c = stack[--top];             /* black once its references are pushed */
        gc_stats.visited++;
        for (int k = 0; k < 2; k++) {
            int d = heap[c].ref[k];
            if (d != NIL && heap[d].meta == WHITE) {
                heap[d].meta = MARKED;
                stack[top++] = d;
            }
        }
    }
}

static void sweep(void)
{
    for (int c = 0; c < size; c++) {
        if (heap[c].meta == MARKED) {
            heap[c].meta = WHITE;         /* ready for the next collection */
        } else if (heap[c].meta == WHITE) {  /* unreachable: garbage */
            heap[c] = (struct cell){FREE, 0, {free_list, NIL}};
            free_list = c;
            gc_stats.swept++;
        }
    }
}
Listing 9.5. Mark with an explicit stack: a grey cell is a marked cell still on the stack. Sweep visits every cell of the heap. code/bachelor-3/09-garbage-collection/listings/marksweep.c

Theorem 9.6 (Marking is correct)

The marking loop of Listing 9.5 keeps the tri-colour invariant, and it stops with every reachable cell black and every other cell white.

Proof. Grey cells are exactly the cells on the stack: a cell is marked when it is pushed and becomes black when it is popped and its two references examined. At the start nothing is black. One iteration pops a grey cell cc and examines its references; every white one is marked and pushed, so becomes grey. Afterwards cc is black and refers to no white cell; no other black cell changed or lost a black neighbour’s colour, since colours only go from white to grey to black. So the invariant holds after every iteration. Each cell is pushed at most once, when it stops being white, so the loop stops, with an empty stack: no grey cell. Take a reachable cell xx and a path r=x0,x1,…,xk=xr = x_0, x_1, \dots, x_k = x from a root. x0x_0 was made grey by the first loop, so it is black at the end. If xix_i is black, xi+1x_{i+1} is not white by the invariant, and not grey since none is left: it is black. By induction xx is black. Conversely a cell becomes grey only when reached from a root or from a grey cell, so every marked cell is reachable. ∎

The invariant is what makes marking safe to interleave with the program, the subject of collectors that run alongside it: the program may change references while marking is under way, and it must then never store a reference to a white cell into a black one without telling the collector (exercise 9.11 meets the same constraint in another form). The explicit stack can hold every cell of the heap; a collector that cannot afford such a stack marks with a bounded one, and when it overflows, it rescans the heap for marked cells whose references still point to white ones.

$ gcc -std=c17 -O2 -Wall -Wextra -o ms_demo ms_demo.c marksweep.c -lm && ./ms_demo
collection 1 during request   93: marked  744, swept 2256
collection 2 during request  164: marked 1208, swept 1792
collection 3 during request  220: marked 1208, swept 1792
collection 4 during request  276: marked 1208, swept 1792
collection 5 during request  332: marked 1208, swept 1792
collection 6 during request  388: marked 1208, swept 1792
2000 requests: 64000 cells allocated, 34 collections, 40608 marked, 61392 swept
Output 9.3. The server on a heap of 3,000 cells: 150 sessions of 8 cells, each closed into a cycle, and 24 cells of work per request. In the steady state a collection marks the 1,208 live cells and sweeps the other 1,792.

Every session is a cycle, and the collector frees them anyway, since a cycle that no root reaches is garbage like any other cell. The cost of one collection is the number of reachable cells for marking plus the size of the whole heap for sweeping; between two collections, the program allocates the cells that were swept.

9.4 Copying and generational collection

Definition 9.7 (Copying collector, forwarding pointer)

A copying collector splits the heap into two halves, from-space, where the program allocates, and to-space, kept empty. A collection copies every reachable cell of from-space into to-space, updates every reference to point at the copies, and swaps the two halves’ roles. When a cell is copied, its old place receives a forwarding pointer, the address of the copy, so that later references to it are redirected instead of copying it twice.

Cheney’s algorithm does it breadth first with no stack: the cells copied into to-space form the queue. Two indices walk to-space: next, where the next copy goes, and scan, the first copied cell whose references have not been updated. The cells before scan are black, those between scan and next grey, and from-space cells without a forwarding pointer white (Listing 9.6).

static int forward(int c, int *next)  /* the cell's new index, copying it the first time */
{
    if (c == NIL) return NIL;
    if (from[c].meta == NIL) {      /* not copied yet */
        to[*next] = from[c];
        from[c].meta = (*next)++;   /* leave a forwarding pointer behind */
        gc_stats.visited++;
    }
    return from[c].meta;
}

static void collect(void)
{
    int scan = 0, next = 0;
    for (int r = 0; r < nroots; r++) roots[r] = forward(roots[r], &next);
    while (scan < next) {           /* to-space cells between scan and next are grey */
        for (int k = 0; k < 2; k++) to[scan].ref[k] = forward(to[scan].ref[k], &next);
        scan++;
    }
    struct cell *t = from;
    from = to;
    to = t;
    top = next;
    gc_stats.collections++;
}
Listing 9.6. Cheney’s algorithm: forward the roots, then scan to-space until the scan index catches up with the free index. code/bachelor-3/09-garbage-collection/listings/cheney.c
Cheney’s algorithm on the graph of exercise , after the root A was copied and scanned. A’s references were forwarded: B and C were copied and their old places hold forwarding pointers (to cells 1 and 2). E, garbage, is never touched. Scanning B next will copy D to cell 3.
Cheney’s algorithm on the graph of exercise 9.8, after the root A was copied and scanned. A’s references were forwarded: B and C were copied and their old places hold forwarding pointers (to cells 1 and 2). E, garbage, is never touched. Scanning B next will copy D to cell 3.

Theorem 9.8 (Cheney’s algorithm)

A collection copies each cell reachable from the roots exactly once, and no other, leaves every reference pointing at the copy of its target, and does work proportional to the number of reachable cells plus the number of roots.

Proof. A cell is copied only by forward, the first time a reference to it is forwarded; the forwarding pointer it leaves makes every later call return the same copy. Each copy is scanned once, when scan passes it, and each of its two references is then forwarded, so the set of copied cells is closed under references and contains the roots’ targets: it contains every reachable cell. Conversely a cell is copied only when a root or a copied cell refers to it, so every copied cell is reachable. Every reference in to-space and every root was forwarded, so points at a copy. The work is one forward per root and two per copied cell, each in constant time. Garbage is never examined. ∎

This is the copying collector’s great property: its cost does not depend on the amount of garbage. Output 9.4 runs the server’s workload of Output 9.3 under it, on the same 3,000 cells.

$ gcc -std=c17 -O2 -Wall -Wextra -o cheney_demo cheney_demo.c cheney.c -lm && ./cheney_demo
collection 1 during request   46: copied  372
collection 2 during request   82: copied  660
collection 3 during request  108: copied  876
collection 4 during request  127: copied 1020
collection 5 during request  142: copied 1140
collection 6 during request  154: copied 1204
2000 requests: 64000 cells allocated, 211 collections, 253732 copied
Output 9.4. The same workload on a copying heap of 3,000 cells, so 1,500 per half. A collection copies the live cells and nothing else.

On the same memory the copying collector runs 211 collections instead of 34, because the program has only half of it: after copying 1,204 live cells, only 296 are free in from-space. The weekend problem prices that half: exercise 9.10 proves that with LL live cells in a heap of HH cells, the copying collector copies L/(H/2−L)L/(H/2 - L) cells per cell allocated.

Most objects die young: the work list of a request is garbage before the request ends. Generational collectors bet on this generational hypothesis: collecting the young objects often and the old ones rarely spends little time on objects that survive.

Definition 9.9 (Generational collection, write barrier, remembered set)

A generational collector allocates in a small nursery and collects it alone in a minor collection, which moves its survivors into an old generation (promotion); a major collection collects the whole heap. The remembered set holds the old objects that may refer to nursery objects; a minor collection treats them as roots. A write barrier is code run at every store of a reference into an object; here, it adds the object to the remembered set when an old object receives a reference to a young one.

Without the remembered set, a minor collection would have to trace the whole old generation to find the references into the nursery, and would no longer be minor. In gen.c a minor collection is Cheney’s loop applied to the nursery only, copying into the free end of the old generation (Listing 9.7); a reference to an old cell is left as it is.

static int copy(int c, int *next, int all)  /* forward c to *next if it must move */
{
    if (c == NIL || !(all || young(c))) return c;
    if (mem[c].meta == NIL) {
        mem[*next] = mem[c];
        mem[c].meta = (*next)++;
    }
    return mem[c].meta;
}

static void scan_from(int scan, int *next, int all)  /* Cheney's loop */
{
    for (int r = 0; r < nroots; r++) roots[r] = copy(roots[r], next, all);
    for (; scan < *next; scan++)
        for (int k = 0; k < 2; k++) mem[scan].ref[k] = copy(mem[scan].ref[k], next, all);
}

static void minor(void)  /* nursery -> old */
{
    int start = top;
    for (int i = 0; i < nremembered; i++)  /* the remembered cells are roots too */
        for (int k = 0; k < 2; k++)
            mem[remembered[i]].ref[k] = copy(mem[remembered[i]].ref[k], &top, 0);
    nremembered = 0;
    scan_from(start, &top, 0);
    promoted += top - start;
    young_top = 2 * old;
    minors++;
}
Listing 9.7. The generational collector’s two pieces of Cheney: copy moves a cell only if it is young, or in a major collection; a minor collection starts from the remembered cells and the roots. code/bachelor-3/09-garbage-collection/listings/gen.c
Two generations. The store of a reference to the young cell y into the old cell s goes through the write barrier, which adds s to the remembered set. The next minor collection starts from the roots and from s, so it promotes y; the grey cell, which nothing refers to, is never examined.
Two generations. The store of a reference to the young cell yy into the old cell ss goes through the write barrier, which adds ss to the remembered set. The next minor collection starts from the roots and from ss, so it promotes yy; the grey cell, which nothing refers to, is never examined.

The workload run here has no cyclic sessions, so the server never stores into a cell after creating it: a new cell can only refer to older ones and its remembered set stays empty; exercise 9.11 writes the barrier for a program that does store. Output 9.5 runs the weekend problem’s workload, with 2,000 live cells, under the generational collector with 12,000 cells in all.

$ gcc -std=c17 -O2 -Wall -Wextra -o gen_demo gen_demo.c gen.c -lm && ./gen_demo
 nursery   minor   major  promoted  copied major  copied/alloc
     250    1257      22     83416         44000         0.398
     500     616      23     78848         46072         0.390
    1000     291      28     73916         56112         0.406
    2000     121      38     60500         76000         0.427
Output 9.5. The generational collector with nurseries of 250 to 2,000 cells: minor and major collections, cells promoted by minors and copied by majors, and all copies per cell allocated.

The copying collector on the same 12,000 cells copies 0.492 cells per cell allocated (Output 9.7 below); the generational one 0.390 to 0.427. The gain is modest because the hypothesis is only three quarters true here: 4 of every 16 cells belong to a session, which lives for the next 500 requests, so every minor collection promotes them, and the old generation fills with sessions that die there. When nearly everything dies young, minor collections copy almost nothing and the gain is large; the program decides.

9.5 Memory safety without a collector

The Year 2 volume’s Rust frees a value when its single owner goes out of scope, which the compiler checks: no counts, no tracing, and no pause. For a value with several owners, Rust offers Rc, a reference-counted pointer, with the weakness of every count: a cycle between Rc pointers is never freed. Its remedy is Weak, a reference that does not count: Weak::upgrade returns None once the value is gone (Listing 9.8).

fn main() {
    println!("strong cycle:");
    {
        let (ann, bob) = (member("Ann"), member("Bob"));
        *ann.friend.borrow_mut() = Some(Rc::clone(&bob));
        *bob.friend.borrow_mut() = Some(Rc::clone(&ann));
        println!("  counts {} {}", Rc::strong_count(&ann), Rc::strong_count(&bob));
    } // the two locals go; each count falls to 1, never to 0
    println!("  (end of scope: nothing dropped)");

    println!("weak back pointer:");
    let cleo = member("Cleo");
    {
        let dan = member("Dan");
        *cleo.friend.borrow_mut() = Some(Rc::clone(&dan));
        *dan.sponsor.borrow_mut() = Rc::downgrade(&cleo);
        println!("  counts {} {}, weak {}", Rc::strong_count(&cleo), Rc::strong_count(&dan),
                 Rc::weak_count(&cleo));
    }
    let alive = cleo.friend.borrow().as_ref().map(|d| d.sponsor.borrow().upgrade().is_some());
    println!("  Dan's sponsor still there: {:?}", alive);
    drop(cleo); // Cleo's count reaches 0: Cleo dropped, then Dan
    println!("end of main");
}
Listing 9.8. Two members who are each other’s friend are never dropped. A member who holds his sponsor by a Weak pointer does not keep her alive. code/bachelor-3/09-garbage-collection/listings/rc_cycle.rs
$ rustc --edition 2021 -O -o rc_cycle rc_cycle.rs && ./rc_cycle
strong cycle:
  counts 2 2
  (end of scope: nothing dropped)
weak back pointer:
  counts 1 2, weak 1
  Dan's sponsor still there: Some(true)
  drop Cleo
  drop Dan
end of main
Output 9.6. Ann and Bob leak: nothing is printed when their scope ends. Cleo and Dan are dropped as soon as Cleo’s last strong count goes.

Rust’s documentation gives the rule for a tree: strong pointers from a parent to its children, weak ones from a child back to its parent. A third way avoids per-object freeing altogether: an arena, a region in which a computation allocates freely and which is freed in one step when the computation ends, as a compiler does with a whole syntax tree. Table 9.1 sums up what each strategy costs.

strategycost on each pointer storecost of reclaimingcycleswhen memory returns
manual freenoneconstant per blockthe programmer’s jobwhen the program says
countingtwo counts updatedconstant per objectleakat once
mark and sweepnonelive objects + whole heapfreedat a collection
copyingnonelive objects only; half the memory idlefreedat a collection
generationala write barrierlive young objects, rare majorsfreedat a collection
ownershipnone (checked by the compiler)constant per objectimpossible without Rcend of the owner’s scope
arenanoneone step for the arenafreed with itwhen the arena goes
Table 9.1. What each way of managing memory costs, and when.

History — Collectors

Two papers of 1960 on list processing stand at the start: John McCarthy’s Recursive functions of symbolic expressions and their computation by machine in April, and George Collins’s A method for overlapping and erasure of lists in December. C. J. Cheney published his nonrecursive list compacting algorithm in November 1970. Edsger Dijkstra, Leslie Lamport, A. J. Martin, C. S. Scholten and E. F. M. Steffens published on-the-fly garbage collection in 1978. Henry Lieberman and Carl Hewitt described a real-time garbage collector based on the lifetimes of objects in 1983, and David Ungar generation scavenging in 1984.

9.6 Exercises

Exercise 9.1 ★

An arena holds, in address order, free blocks of 96, 48, 160 and 64 bytes, separated by used blocks, then one large free block. Requests of 40, 24, 130 and 80 bytes arrive in that order; each needs a block of its size plus 16 bytes of tags, rounded up to 16. Which block does each one take under first fit, and under best fit?

Solution

Solution of Exercise 9.1.

The requests need blocks of 64, 48, 160 and 96 bytes. First fit: 64 from the block of 96, which is split into 64 and a free 32; 48 in the block of 48; 160 in the block of 160; and 96 finds only the free 32, the 64 and the large block, so it cuts into the large block. Best fit: 64 in the block of 64, 48 in the 48, 160 in the 160, and 96 in the block of 96, every one an exact fit. Best fit leaves the large block whole; first fit leaves a sliver of 32 bytes and a hole of 64 (arena_test.c checks the four offsets of each policy).

Exercise 9.2 ★

After a = O(); b = a; c = [a, b]; d = {'k': a}; del a; b = None; c.append(c[0]); d['k'] = None, what is the reference count of the object, and what does sys.getrefcount(c[0]) print?

Solution

Solution of Exercise 9.2.

Three: the list c holds it three times, and the names a, b and the dictionary no longer refer to it. sys.getrefcount prints 4, one more for its own argument.

Exercise 9.3 ★

Roots: r1→Ar_1 \to A and r2→Dr_2 \to D. References: A→BA \to B, B→CB \to C, C→AC \to A, E→FE \to F, F→EF \to E, G→DG \to D. Which objects are garbage? Which of them does reference counting free?

Solution

Solution of Exercise 9.3.

A, B and C are reachable from r1r_1, and D from r2r_2. E, F and G are garbage. Reference counting frees G, whose count is 0 (D’s count then falls from 2 to 1, and D stays). E and F keep each other’s count at 1 and are never freed.

Exercise 9.4 ★

In Listing 9.8, the line that makes Ann Bob’s friend becomes *bob.sponsor.borrow_mut() = Rc::downgrade(&ann);. Predict the first block of the output.

Solution

Solution of Exercise 9.4.

strong cycle:, counts 1 2, drop Ann, drop Bob, then the line that now lies, (end of scope: nothing dropped). Ann’s only strong reference is the local ann; Bob has two, the local and Ann’s friend. When the scope ends, both locals go: whichever goes first, Ann’s count reaches 0, Ann is dropped, and dropping her friend field removes Bob’s last count.

Exercise 9.5 ★★

exercises/ex5_sweep_bug.c is marksweep.c with one line missing. On the workload of Output 9.3 it marks fewer and fewer cells, sweeps fewer and fewer, and runs out of memory during request 367. Find the line, and explain the run.

Solution

Solution of Exercise 9.5.

The missing line is heap[c].meta = WHITE; in sweep: marked cells keep their marks. At the next collection, the first loop of mark skips every root already marked, and the stack never reaches past a marked cell, so only the cells allocated since are examined, and the marked count falls at each collection. Sweep frees only white cells, so every cell that was live at some collection stays allocated forever, even after it dies: a leak that grows at each collection, the swept count falls with it, and the heap is full during request 367, after 17 collections (sweep_bug_test.c). The bug can do worse: a new white cell reachable only through an old marked one is never marked, and the sweep frees a cell the program still uses.

Exercise 9.6 ★★

Write next fit: a placement policy for arena.c that starts each search at the block where the previous one stopped, wrapping round at the end. Why can its saved position become wrong after an arena_free, and how do you keep it right?

Solution

Solution of Exercise 9.6.

exercises/ex6_next_fit.c keeps the block where the last search succeeded, starts there, and wraps round at the epilogue. Freeing can merge the block at that position into the free block before it, or merge it into the freed block as its successor; the position then points into the middle of a block, where the walk would read payload as tags. next_fit_free moves it to the start of the merged block before freeing. nextfit_test.c checks after each of 20,000 random operations that the position is the start of a block, and that a request after a free goes on past the last block used instead of reusing the freed one.

Exercise 9.7 ★★

Using the tri-colour invariant, prove that after mark and sweep the free list holds exactly the cells that were garbage or free before, and that every cell is white again.

Solution

Solution of Exercise 9.7.

By Theorem 9.6, after mark the marked cells are exactly the reachable ones; free cells are never marked, since no reference to them exists. sweep visits every cell once: a marked cell becomes white, a white one (allocated, not reachable: garbage) is pushed on the free list, and a free one is left on the free list where it already is. So the free list ends with the free cells and the garbage, and no cell is marked.

Exercise 9.8 ★★

The heap holds cells D, C, B, A, E, allocated in that order, with A→B,CA \to B, C; B→D,AB \to D, A; C→DC \to D; E→AE \to A. Only A is a root. List the cells Cheney’s algorithm copies, in order, with the new value of every reference.

Solution

Solution of Exercise 9.8.

A is copied to cell 0. Scanning A forwards B (copied to 1) and C (copied to 2). Scanning B forwards D (copied to 3) and A, which already has a forwarding pointer, to 0. Scanning C forwards D to 3; scanning D finds nothing. Four cells are copied, A, B, C, D in that order, and the references become 0→1,20 \to 1, 2; 1→3,01 \to 3, 0; 2→32 \to 3. E is never examined (cheney_test.c).

Exercise 9.9 ★★

Find a short sequence of requests on an arena with two free blocks of 2,000 and 1,504 bytes, in that order, that first fit serves entirely and best fit does not.

Solution

Solution of Exercise 9.9.

Requests for blocks of 1,408, 1,504 and 592 bytes. First fit takes 1,408 from the block of 2,000, leaving 592, puts 1,504 in the block of 1,504 and 592 in what was left: all served. Best fit puts 1,408 in the smaller block, 1,504, leaving 96 bytes nobody can use; 1,504 then goes in the 2,000, leaving 496; the request of 592 is refused, with 592 bytes free in two pieces (arena_test.c).

Exercise 9.10 ★★★

A program keeps exactly LL cells live and allocates without end, in a copying heap of HH cells with H/2>LH/2 > L. Prove that in the steady state the collector copies L/(H/2−L)L/(H/2 - L) cells per cell allocated. What is the analogous cost of mark and sweep, counting one unit per cell marked and one per cell swept?

Solution

Solution of Exercise 9.10.

After a collection from-space holds exactly the LL live cells, copied together, so H/2−LH/2 - L cells are free and the program allocates that many before the next collection. That collection copies the LL cells live then, by Theorem 9.8, and the cycle repeats. Per cell allocated: L/(H/2−L)L/(H/2 - L). For mark and sweep, after a collection the H−LH - L cells not live are free, the next collection comes after H−LH - L allocations, and it marks LL cells and sweeps HH: (L+H)/(H−L)(L + H)/(H - L) units per cell allocated.

Exercise 9.11 ★★★

Write gc_write(c, k, v) for gen.c, a store of the reference vv into field kk of cell cc with a write barrier. Test that an old cell that receives a reference to a young one keeps it alive across a minor collection, and that without the barrier the young cell is lost.

Solution

Solution of Exercise 9.11.

exercises/ex11_barrier.c: if the cell written into is old, the value is a young cell, and the old cell is not yet in the set, it is added; then the store is done. gen.c’s minor collection already forwards the references of the remembered cells first, and empties the set. gen_test.c promotes a cell, stores into it a reference to a new young cell, then allocates past the nursery: with the barrier the young cell is promoted and the reference still finds its value 42; without it the minor collection does not see the reference, the young cell is not copied, and the reference points into a nursery that has been reused.

Exercise 9.12 ★★★

Prove that reference counting frees exactly the garbage objects that cannot be reached from a cycle of garbage objects.

Solution

Solution of Exercise 9.12.

The count of an object is the number of references to it from roots and from objects not yet freed. A reachable object never refers to garbage, otherwise the garbage would be reachable; so the count of a garbage object counts only references from other garbage objects.

Let xx be garbage and not reachable from any garbage cycle. The garbage objects from which xx can be reached form a finite graph with no cycle, otherwise xx would be reachable from that cycle. By induction on the length of the longest path to xx in it: if there is none, xx’s count is 0 and xx is freed; otherwise all the objects that refer to xx are freed, by induction, each decrementing xx’s count, which reaches 0, and xx is freed.

Conversely, suppose an object on a garbage cycle, or reachable from one, is freed, and take the first such object to be freed. If it is on the cycle, its predecessor on the cycle is not yet freed and refers to it; otherwise the object before it on a path from the cycle is not yet freed and refers to it. Either way its count is at least 1 when it is freed, which is impossible. Reachable objects are never freed for the same reason: the root or object before them on a path keeps their count at least 1.

9.7 Weekend problem

Problem 9.1

Weekend problem — Choosing the heap size of the town’s server

The town’s server keeps the sessions of its last 500 requests, 4 cells each; every request also builds 12 cells of work that die with it (Listing 9.9). How much memory should it get? Output 9.7 runs 20,000 requests under the copying collector for heaps of HH cells from 2.5 to 16 times the live data LL; Output 9.8 does the same under mark and sweep.

{
    nroots = keep + 1;
    for (int r = 0; r <= keep; r++) roots[r] = NIL;
}

static int serve(int r, int keep, int sess, int temp, int cyclic)  /* request number r */
{
    if (!build(keep, temp, r, 0) || !build(keep, sess, r, cyclic)) return 0;
    roots[r % keep] = roots[keep];
    roots[keep] = NIL;
    return 1;
}
Listing 9.9. One request of the server: work, then a session that replaces the oldest one. code/bachelor-3/09-garbage-collection/listings/server.h
$ gcc -std=c17 -O2 -Wall -Wextra -o pb_copying pb_copying.c cheney.c -lm && ./pb_copying 2.5 3 4 6 8 12 16
L = 2000 live cells, 20000 requests of 16 cells
  H/L      H collections    copied  copied/alloc    model
  2.5   5000         634   1267304         3.960    3.989
  3.0   6000         318    636320         1.988    2.003
  4.0   8000         158    314756         0.984    0.992
  6.0  12000          79    157504         0.492    0.498
  8.0  16000          52    104000         0.325    0.333
 12.0  24000          31     62000         0.194    0.200
 16.0  32000          22     44000         0.138    0.143
Output 9.7. The copying collector: collections, cells copied, cells copied per cell allocated, and the model L/(H/2−L)L/(H/2 - L) with LL the mean number of cells copied by a collection.
$ gcc -std=c17 -O2 -Wall -Wextra -o pb_marksweep pb_marksweep.c marksweep.c -lm && ./pb_marksweep 1.25 1.5 2 3 4 6 8 16
  H/L      H collections    marked     swept  work/alloc    model
 1.25   2500         634   1267304    317696       8.913    8.978
 1.50   3000         318    636320    317680       4.970    5.006
 2.00   4000         158    314756    317244       2.959    2.984
 3.00   6000          79    157504    316496       1.973    1.995
 4.00   8000          52    104000    312000       1.625    1.667
 6.00  12000          31     62000    310000       1.356    1.400
 8.00  16000          22     44000    308000       1.238    1.286
16.00  32000          10     20000    300000       1.062    1.133
Output 9.8. Mark and sweep on the same requests: cells marked and swept, the work per cell allocated (marked plus the heap swept at each collection), and the model (L+H)/(H−L)(L + H)/(H - L).

Part I — Live data and allocation.

  1. How many cells are live once 500 requests have run, and how many more at most while a request is in progress?
  2. How many cells does one request allocate, and what fraction of them are garbage by the end of the next request?
  3. With cells of 16 bytes, how many bytes are live? How many bytes does the server allocate over the 20,000 requests?
  4. Why is the number of cells copied at a collection close to LL but not always equal to it?
  5. The generational hypothesis: what fraction of the cells die before 16 more cells are allocated? And before 8,000?
  6. Why must the work list being built be a root?

Part II — The copying model.

  1. After a collection, how many cells can the program allocate before the next one?
  2. Derive the cost L/(H/2−L)L/(H/2 - L) cells copied per cell allocated.
  3. What happens to the cost as HH approaches 2L2L? What is the smallest heap that works at all?
  4. Show that for HH much larger than LL the cost is close to 2L/H2L/H, so that doubling the heap halves it.
  5. With L=2,000L = 2{,}000, what heap gives one cell copied per cell allocated?
  6. The memory the program never uses is a cost too. What fraction of a copying heap holds live data at H=4LH = 4L?

Part III — Measured.

  1. Check the model against the measured column for H=2.5LH = 2.5L and H=8LH = 8L.
  2. Why is the measured value slightly below the model for large HH? (Look at the number of collections.)
  3. How many collections would H=32LH = 32L need, by the model?
  4. From H=4LH = 4L to H=8LH = 8L, by what factor does the work fall? From 8L8L to 16L16L?
  5. The total number of copies at H=16LH = 16L is exactly 22 times 2,000. Explain.
  6. If copying a cell costs 20 ns, how much time does the collector spend at H=2.5LH = 2.5L and at H=6LH = 6L over the 20,000 requests?

Part IV — Mark and sweep compared.

  1. Derive the model (L+H)/(H−L)(L + H)/(H - L) for mark and sweep.
  2. Compare the two collectors with the same memory, H=4LH = 4L: which does less work per cell, counting a copy and a sweep step alike?
  3. Why does the mark-and-sweep cost never fall below 1, however large the heap?
  4. A sweep step is cheaper than a copy: it reads one cell and may link it into the free list. If a sweep step costs a quarter of a copy, which collector wins at H=4LH = 4L, and at H=16LH = 16L?
  5. What does the copying collector give in exchange for its idle half, besides speed?
  6. Sum up: what heap size do you give the server, and why?
Solution

Solution of Problem 9.1.

1. 500×4=2,000500 \times 4 = 2{,}000 cells, so L=2,000L = 2{,}000. While a request runs, at most 12 more: the work list as it is built; by the time the new session is built, the work list is already garbage, and the 4 session cells replace the work list’s.

2. 12+4=1612 + 4 = 16 cells; the 12 cells of work, 75 %, are garbage once the request ends.

3. 2,000×16=32,0002{,}000 \times 16 = 32{,}000 bytes live; 20,000×16=320,00020{,}000 \times 16 = 320{,}000 cells allocated, 5,120,0005{,}120{,}000 bytes.

4. A collection may come in the middle of a request, when up to 12 more cells are live, and during the first 500 requests fewer than 500 sessions exist.

5. 75 % die within the 16 allocations of their own request; the other 25 % after 500 requests, about 8,000 allocations. The hypothesis holds for three cells out of four.

6. Every allocation may collect. A reference held only in a C variable would not be seen by the collector: the list’s cells would be garbage to it, freed or, under copying, left behind while the variable still points at the old place.

7. H/2−LH/2 - L.

8. Each collection copies LL cells and is followed by H/2−LH/2 - L allocations: L/(H/2−L)L/(H/2 - L) per cell allocated (exercise 9.10).

9. It grows without bound: each collection frees almost nothing. Half the heap must hold the live data and a request in progress, 2,0122{,}012 cells, so H≥2×2,012=4,024H \ge 2 \times 2{,}012 = 4{,}024 at the very least.

10. L/(H/2−L)=2L/(H−2L)L/(H/2 - L) = 2L/(H - 2L), which is close to 2L/H2L/H when HH is much larger than 2L2L; that is halved when HH doubles.

11. L/(H/2−L)=1L/(H/2 - L) = 1 gives H=4L=8,000H = 4L = 8{,}000 cells, 128 KB; the measurement gives 0.984.

12. A quarter: half of the heap is to-space, empty, and from-space is half live data just after a collection.

13. At 2.5L2.5L: 3.960 measured, 3.989 by the model; at 8L8L: 0.325 and 0.333. Both within 3 %.

14. The cells allocated after the last collection are counted in the allocations but have not paid for a collection yet. At 16L16L: 22 collections pay for 22×14,000=308,00022 \times 14{,}000 = 308{,}000 allocations, and 12,000 more are free riders. The larger the heap, the larger that last partial cycle, relative to the run.

15. H/2−L=30,000H/2 - L = 30{,}000, so a collection every 30,000 allocations after the first, which comes at 32,000: 10 collections in 320,000 allocations.

16. 0.984/0.325≈3.00.984/0.325 \approx 3.0, then 0.325/0.138≈2.40.325/0.138 \approx 2.4: a doubling divides the work by more than 2, and the factor tends to 2 as HH grows.

17. A collection comes when from-space is full: the first after 16,000 allocations, which is 1,000 requests, the next every 16,000−2,000=14,00016{,}000 - 2{,}000 = 14{,}000 allocations, which is 875 requests. Every collection falls exactly between two requests, when exactly 2,000 cells are live.

18. 1,267,304×201{,}267{,}304 \times 20 ns ≈25\approx 25 ms at 2.5L2.5L; 157,504×20157{,}504 \times 20 ns ≈3.2\approx 3.2 ms at 6L6L.

19. After a collection, the H−LH - L cells not live are free; the program allocates them; the next collection marks LL and sweeps HH. Per cell allocated, (L+H)/(H−L)(L + H)/(H - L).

20. Copying: 0.984 copies per cell allocated; mark and sweep: 1.625 units (model 5/35/3). Counted alike, copying does less work, because it never visits the garbage.

21. The sweep visits every cell of the heap, and each collection frees at most H−LH - L of them: at least H/(H−L)>1H/(H - L) > 1 sweep steps per cell allocated.

22. With a sweep step at a quarter of a copy and a mark at a copy, mark and sweep costs (L+H/4)/(H−L)(L + H/4)/(H - L): at 4L4L, 2L/3L=0.672L/3L = 0.67, less than copying’s 1; at 16L16L, 5L/15L=0.335L/15L = 0.33, more than copying’s L/7L=0.14L/7L = 0.14. Mark and sweep wins on a tight heap, copying on a large one.

23. Compaction: the live cells end up together and the free memory is one block, so allocation is a pointer increment and there is no external fragmentation; the copies also sit near each other in breadth-first order.

24. With copying, the work per cell allocated is L/(H/2−L)L/(H/2 - L), measured within 3 %; it is 1 at 4L4L, and each doubling of the heap beyond that divides it by 3, then by 2.4, then by nearly 2. 8L8L = 16,000 cells (256 KB) costs one copy for every three cells allocated, about 2 ms of collection for 20,000 requests at 20 ns a copy; going to 16L16L saves about 1.2 ms more for twice the memory. For a server with this much live data, 6L6L to 8L8L is the sensible choice; below 4L4L the collector’s work grows quickly.

এই অধ্যায়ে সংজ্ঞায়িত পরিভাষা-শব্দ

পরিভাষায় সব 1050 টি শব্দ দেখো