---
title: "PostgreSQL启动过程中的那些事七：初始化共享内存和信号十三：shmem中初始化SharedInvalidationState"
author: "BeiGang"
date: "2012-03-14T20:34:52Z"
tags: []
categories: ["数据库"]
slug: "postgresql-shmem-sharedinvalidationstate"
draft: false
lastmod: "2012-03-14T20:35:53Z"
id: 1453744
url: "https://beigang.iteye.com/blog/1453744"
---

这一节 pg 初始化管理共享失效信息状态缓存所用到的相关结构，通过 CreateSharedInvalidationState 例程实现。共享失效消息主要涉及系统目录、逻辑表、物理表文件、数据库等。

 

**1** **先上个图，看一下函数调用过程梗概，中间略过部分细节**

![](http://dl.iteye.com/upload/attachment/0064/8420/4965aff6-5593-3f34-935b-abab0cfacb9f.bmp)

初始化共享失效状态缓存方法调用流程图

 

**2** **初始化** **xlog** **相关结构**

话说 main()-&gt; … -&gt;PostmasterMain()-&gt; … -&gt;reset\_shared() -&gt; CreateSharedMemoryAndSemaphores()&gt; … -&gt;CreateSharedInvalidationState() ，调用 ShmemInitStruct() ， 在其中 调用 hash\_search() 在哈希表索引 "ShmemIndex" 中查找 "shmInvalBuffer" ，如果没有，就在 shmemIndex 中给 "shmInvalBuffer" 分一个 HashElement 和 ShmemIndexEnt （ entry ） ，在其中的 Entry 中写上 "shmInvalBuffer" 。返回 ShmemInitStruct() ，再调用 ShmemAlloc() 在共享内存上给 "shmInvalBuffer" 相关结构（见下面“ shmInvalBuffer 相关结构图” ）分配空间，设置 entry （在这儿及ShmemIndexEnt 类型变量）的成员 location 指向该空间， size 成员记录该空间大小 ， 最后返回 CreateSharedInvalidationState () ，让 SISeg * 类型静态 全局变量 shmInvalBuffer 指向 所分配内存 ，设置SISeg 和ProcState 结构类型的成员值。

相关结构定义见下面：

/* Shared cache invalidation memory segment \*/

**typedef** **struct** SISeg

{

    /*

      * General state information

      \*/

    **int**         minMsgNum ;    /* oldest message still needed \*/

    **int**         maxMsgNum ;    /* next message number to be assigned \*/

    **int**         nextThreshold ;    /* # of messages to call SICleanupQueue \*/

    **int**         lastBackend ;  /* index of last active procState entry, +1 \*/

    **int**         maxBackends ;  /* size of procState array \*/

 

    slock\_t        msgnumLock ;       /* spinlock protecting maxMsgNum \*/

 

    /*

      * Circular buffer holding shared-inval messages

      \*/

    SharedInvalidationMessage buffer \[MAXNUMMESSAGES];

 

    /*

      * Per-backend state info.

      *

      * We declare procState as 1 entry because C wants a fixed-size array, but

      * actually it is maxBackends entries long.

      \*/

    ProcState   procState \[1]; /* reflects the invalidation state \*/

} SISeg ;

 

**static** SISeg \*shmInvalBuffer;   /* pointer to the shared inval buffer \*/

   
![](http://dl.iteye.com/upload/attachment/0064/8424/0cb7be09-8121-3564-9a4e-c4206803b269.bmp)

 

初始化完 shmInvalBuffer 相关结构 的共享内存结构图

       为了精简上图，把创建 shmem 的哈希表索引 "ShmemIndex" 时创建的 HCTL 结构删掉了，这个结构的作用是记录创建可扩展哈希表的相关信息，不过这个结构在 "ShmemIndex" 创建完成后也会由于出了对象作用域而消失。增加了左边灰色底的部分，描述 共享内存 /shmem 里各变量物理布局概览，由下往上，由低地址到高地址。 图中黄色的索引项就是本节新增加的索引项。

 

![](http://dl.iteye.com/upload/attachment/0064/8418/508c541a-e4fa-3b69-b2fd-b858fdd8c777.bmp)

shmInvalBuffer 相关结构图