Garbage Collection

来源:互联网 发布:拉吉普特级驱逐舰知乎 编辑:程序博客网 时间:2024/05/21 14:51

A garbage collector is a dynamic storage allocator that automatically frees allocated blocks that are no longer needed by the program. We introduce Mark&Sweep garbage collectors here.

      A Mark&Sweep garbage collector consists of a mark phase, which marks all reachable and allocated descendants of the root nodes, followed by a sweep phase, which frees each unmarked allocated block. Typically, one of the spare low-order bits in the block header is used to indicate whether a block is marked or not. Our description of Mark&Sweep will assume the following functions, where ptr is defined as typedef void *ptr.

        ptr isPtr(ptr p): If  p points to some word in an allocated block, returns a pointer b to the beginning of that block. Returns NULL otherwise.
        int blockMarked(ptr b): Returns true if block b is already marked.
        int blockAllocated(ptr b): Returns true if block b is allocated.
        void markBlock(ptr b): Marks block b.
        int length(b): Returns the length in words (excluding the header) of block b.
        void unmarkBlock(ptr b): Changes the status of block b from marked to unmarked.
        ptr nextBlock(ptr b): Returns the successor of block b in the heap.

And the pseudo-code for the mark and sweep functions is listed below.

(a) mark function                    (b) sweep function               void mark(ptr p) {                   void sweep(ptr b, ptr end) {    if ((b = isPtr(p)) == NULL)          while (b < end) {                   return;                              if (blockMarked(b))             if (blockMarked(b))                          unmarkBlock(b);                     return;                              else if (blockAllocated(b))     markBlock(b);                                free(b);                        len = length(b);                         b = nextBlock(b);               for (i=0; i!=len; ++i)               }                                   mark(b[i]);                      return;                         return;                          }                           }
      The mark phase calls the mark function once for each root node. The mark function returns immediately if  p does not point to an allocated and unmarked heap block. Otherwise, it marks the block and calls itself recursively on each word in block. Each call to the mark function marks any unmarked and reachable descendants of some root node. At the end of the mark phase, any allocated block that is not marked is guaranteed to be unreachable, and hence garbage that can be reclaimed in the sweep phase.

      The sweep phase is a single call to the sweep function shown above. The sweep function iterates over each block in the heap, freeing any unmarked allocated blocks (i.e., garbage) that it encounters.

0 0
原创粉丝点击