loyalxuan 发表于 2016-11-21 07:37:16

PostgreSQL的内存管理机制二:AllocSet/MemoryContext的内存回收

  话说MemoryContextMethods结构里的函数实现了pg里AllocSet/MemoryContext的内存管理机制,定义见下面。
  typedef structMemoryContextMethods
  {
  void*(*alloc) (MemoryContext context, Sizesize);
  /* call this free_p in case someone #define's free() */
  void (*free_p)(MemoryContext context, void *pointer);
  void*(*realloc) (MemoryContext context, void *pointer, Size size);
  void (*init)(MemoryContext context);
  void (*reset)(MemoryContext context);
  void (*delete) (MemoryContext context);
  Size (*get_chunk_space) (MemoryContext context, void *pointer);
  bool (*is_empty)(MemoryContext context);
  void (*stats)(MemoryContext context);
  #ifdef MEMORY_CONTEXT_CHECKING
  void (*check)(MemoryContext context);
  #endif
  } MemoryContextMethods;
  其中free_p由静态函数AllocSetFree()实现,具体签名在下面。它实现了AllocSet/MemoryContext相关的内存回收机制。
  static void AllocSetFree(MemoryContext context, void *pointer)
  下面就写MemoryContextMethods.free_p的实现者AllocSetFree()这个函数。先上图,然后分块解读处理流程。
  

  AllocSetFree回收内存流程图
  传进来了AllocSet和内存指针,根据该内存指针,找到对应的AllocChunk,检查该chunk中是否有非法写的情况,若有,在日志中写警告记录。接着检查该chunk大小是否大于chunk的最大值8k,把小于8k的AllocChunk加到传进来的AllocSet中空闲AllocChunk链表数组freelist中同样大小的AllocChunk链表头部。大于8k的AllocChunk是根据需要分配的只包含一个AllocChunk的AllocBlock,找到包含超大AllocChunk的AllockBlock,释放该AllocBlock以备其他需要时malloc,如果没有找到大于8k的AllocChunk的AllocBlock,在日志中写错误记录。具体看流程图吧。
页: [1]
查看完整版本: PostgreSQL的内存管理机制二:AllocSet/MemoryContext的内存回收