這一節 pg 初始化 BTree 用到的相關結構,通過 BTreeShmemInit 例程實作 。主要是初始化了一個 BTVacInfo 結構,并使用了面向過程C 語言程式設計的一個技巧,把這個結構中的固定長度數組 BTOneVacInfo vacuums[1] 擴充成 MaxBackends 個(根據預設值 100 或 GUC 參數的設定得到)的 BTOneVacInfo 結構的數組,以供 BTree 使用。
pg 中相關 BTree 部分實作了 Lehman 和 Yao 的高并發 B-tree 管理算法( P. Lehman and S. Yao,Efficient Locking for Concurrent Operations on B-Trees, ACM Transactions on Database Systems, Vol 6, No. 4, December 1981, pp 650-670 )。還用了 Lanin 和 Shasha 論文裡所寫的删除邏輯的簡化版本( V. Lanin and D. Shasha, A Symmetric Concurrent B-Tree Algorithm, Proceedings of 1986 Fall Joint Computer Conference, pp 380-389 )。。
1 先上個圖,看一下函數調用過程梗概,中間略過部分細節
初始化 BTree 相關結構方法調用流程圖
2 初始化 xlog 相關結構
話說 main()-> … ->PostmasterMain()-> … ->reset_shared() -> CreateSharedMemoryAndSemaphores()> … -> BTreeShmemInit() ,調用 ShmemInitStruct() , 在其中 調用 hash_search() 在哈希表索引 "ShmemIndex" 中查找 "BTree Vacuum State" ,如果沒有,就在 shmemIndex 中給 "BTree Vacuum State" 分一個 HashElement 和 ShmemIndexEnt ( entry ) ,在其中的 Entry 中寫上 "BTree Vacuum State" 。傳回 ShmemInitStruct() ,再調用 ShmemAlloc() 在共享記憶體上給 "BTree Vacuum State" 相關結構(見下面“ BTree Vacuum State 相關結構圖” )配置設定空間,設定 entry (在這兒及ShmemIndexEnt 類型變量)的成員 location 指向該空間, size 成員記錄該空間大小 , 最後傳回 BTreeShmemInit () ,讓 BTVacInfo * 類型靜态 全局變量 btvacinfo 指向 所配置設定記憶體 ,初始化BTVacInfo 結構類型的成員值。
相關結構定義和圖見下面:
typedef struct BTOneVacInfo
{
LockRelId relid ;
BTCycleId cycleid ;
} BTOneVacInfo ;
typedef struct BTVacInfo
{
BTCycleId cycle_ctr ;
int num_vacuums ;
int max_vacuums ;
BTOneVacInfo vacuums [1];
} BTVacInfo ;
static BTVacInfo *btvacinfo;
初始化完 BTree Vacuum State 相關結構 的共享記憶體結構圖
為了精簡上圖,把建立 shmem 的哈希表索引 "ShmemIndex" 時建立的 HCTL 結構删掉了,這個結構的作用是記錄建立可擴充哈希表的相關資訊,不過這個結構在 "ShmemIndex" 建立完成後也會由于出了對象作用域而消失。增加了左邊灰色底的部分,描述 共享記憶體 /shmem 裡各變量實體布局概覽,由下往上,由低位址到高位址。 圖中黃色的索引項就是本節新增加的索引項。
BTree Vacuum State 相關結構圖