话说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,在日志中写错误记录。具体看流程图吧。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。