ITeye博客

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

BeiGang · 2011-12-09 20:29 · PostgreSQL内核 · 数据库 · Markdown

话说 MemoryContextMethods 结构里的函数实现了pg 里AllocSet/MemoryContext 的内存管理机制,定义见下面。

typedef struct MemoryContextMethods

{

     void    *(*alloc) (MemoryContext context, Size size);

     /* 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 ,在日志中写错误记录。具体看流程图吧。

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。