PostgreSQL 内存上下文 MemoryContext
MemoryContext 是 PG 内存上下文管理模块,内核代码可以在指定的 MemoryContext 上动态分配内存,扩容内存以及释放内存,使用 MemoryContext 便于内存管理,内存使用统计以及防止内存泄露。
PG 内核代码中大量使用的 palloc,repalloc,pfree 等都是基于 MemoryContext 内存管理机制对动态申请的内存进行管理。
1. MemoryContext 结构
MemoryContext 是一个指向 MemoryContextData 结构体的指针类型。
typedef struct MemoryContextData
{
NodeTag type; /* identifies exact kind of context */
/* these two fields are placed here to minimize alignment wastage: */
bool isReset; /* T = no space alloced since last reset */
bool allowInCritSection; /* allow palloc in critical section */
Size mem_allocated; /* track memory allocated for this context */
const MemoryContextMethods *methods; /* virtual function table */
MemoryContext parent; /* NULL if no parent (toplevel context) */
MemoryContext firstchild; /* head of linked list of children */
MemoryContext prevchild; /* previous child of same parent */
MemoryContext nextchild; /* next child of same parent */
const char *name; /* context name (just for debugging) */
const char *ident; /* context ID if any (just for debugging) */
MemoryContextCallback *reset_cbs; /* list of reset/delete callbacks */
} MemoryContextData;
typedef struct MemoryContextData *MemoryContext;