海山数据库(He3DB)源码详解:MemoryContextData及MemoryContextMethods结构体解析
MemoryContextData
结构体的作用
MemoryContextData
是 PostgreSQL 中用于实现内存上下文(Memory Context)的核心结构体。内存上下文是 PostgreSQL 的内存管理机制,用于高效地分配和释放内存,支持嵌套内存上下文,并允许在事务或函数结束时批量释放内存。
其中,main
函数会调用MemoryContextInit
函数初始化全局变量TopMemoryContext
,之后的内存申请基本可以从这个全局变量中获得。
结构体定义:
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;
以下是对 MemoryContextData
结构体及其成员的详细解读:
结构体成员:
1. type
NodeTag type; /* identifies exact kind of context */
- 类型:
NodeTag
- 作用:标识内存上下文的具体类型。
- 说明:PostgreSQL 提供了多种类型的内存上下文实现(如
AllocSetContext
、SlabContext
等)。type
字段用于区分当前上下文的具体实现类型。
2. isReset
bool isReset; /* T = no space alloced since last reset */
- 类型:
bool
- 作用:标记自上次重置(reset)以来是否分配了内存。
- 说明
- 如果自上次调用
MemoryContextReset
以来没有分配内存,则该值为true
。 - 这个字段用于优化内存管理,避免不必要的重置操作。
- 如果自上次调用
3. allowInCritSection
bool allowInCritSection; /* allow palloc in critical section */
- 类型:
bool
- 作用:标记是否允许在关键部分(critical section)中分配内存。
- 说明:
- 关键部分是指不允许中断的代码区域,通常用于确保操作的原子性。
- 如果设置为
true
,则允许在关键部分中使用palloc
等内存分配函数。
4. mem_allocated
Size mem_allocated; /* track memory allocated for this context