---
title: "pg的内存管理机制二：AllocSet/MemoryContext的内存回收"
author: "BeiGang"
date: "2011-12-09T20:29:29Z"
tags: []
categories: ["数据库"]
slug: "pg-allocset-memorycontext"
draft: false
lastmod: "2011-12-09T20:30:25Z"
id: 1300207
url: "https://beigang.iteye.com/blog/1300207"
---

话说 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() 这个函数。先上图，然后分块解读处理流程。

![](http://dl.iteye.com/upload/attachment/603568/9900accb-22ca-39c7-925f-12c972eb19dc.png)

 

AllocSetFree 回收内存流程图

 

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