散列表 哈希算法 数据结构 c++ cmu15445 2027fall project2 详细过程(下)Extendible Hash Table - 2014
project2下
Task 3 Extendible Hash Table1 总体介绍2 代码详解2.1头文件2.2 Init2.3 Getvalue2.4 Insert2.5 Update2.6 SplitBucket2.7 Remove
Task 4 Concurrency Control需要注意的点:
Task 3 Extendible Hash Table
1 总体介绍
通过申请读写页的方式来管理增删改查、申请新页来管理分裂桶、删除空页合并桶
2 代码详解
2.1头文件
2.1.1各种变量名含义
变量名含义index_name_不知道,没啥用,到时候赋个值就行BufferPoolManager *bpm_要使用的缓冲区池管理器KC cmp_键的比较器HashFunction hash_fn_哈希函数header_max_depth_头部页面允许的最大深度directory_max_depth_目录页面允许的最大深度bucket_max_size_桶页面允许的最大深度header_page_id_头目录pageid
2.1.2方法列表
变量名含义Init初始化Getvalue在哈希表中查找与给定键相关联的值Insert插入值UpdateDirectoryMapping更新目录索引SpiltBucket分裂桶(自己定义的)Remove移除键值对
2.2 Init
2.2.1 详解 初始化就是把该赋值的赋值,没啥说的 2.2.2 代码
DiskExtendibleHashTable::DiskExtendibleHashTable(const std::string &name, BufferPoolManager *bpm,
const KC &cmp, const HashFunction&hash_fn,
uint32_t header_max_depth, uint32_t directory_max_depth,
uint32_t bucket_max_size)
: bpm_(bpm),
cmp_(cmp),
hash_fn_(std::move(hash_fn)),
header_max_depth_(header_max_depth),
directory_max_depth_(directory_max_depth),
bucket_max_size_(bucket_max_size) {
this->index_name_ = name;
// 初始化header页
header_page_id_ = INVALID_PAGE_ID;
auto header_guard = bpm->NewPageGuarded(&header_page_id_);
auto header_page = header_guard.AsMut();
header_page->Init(header_max_depth_);
}
2.3 Getvalue
2.3.1 详解 看图
2.3.2 代码
// 在哈希表中查找与给定键相关联的值
// key:要查找的键;result:与给定键相关联的值; transaction 当前事务
auto DiskExtendibleHashTable::GetValue(const K &key, std::vector*result, Transaction *transaction) const
->bool {
// 获取header page
ReadPageGuard header_guard = bpm_->FetchPageRead(header_page_id_);
auto header_page = header_guard.As();
// 通过hash值获取dir_page_id。若dir_page_id为非法id则未找到
auto hash = Hash(key);
auto dirIndex = header_page->HashToDirectoryIndex(hash);
page_id_t directory_page_id = header_page->GetDirectoryPageId(dirIndex);
if (directory_page_id == INVALID_PAGE_ID) {
return false;
}
// 获取dir_page
header_guard.Drop();
ReadPageGuard directory_guard = bpm_->FetchPageRead(directory_page_id);
auto directory_page = directory_guard.As();
// 通过hash值获取bucket_page_id。若bucket_page_id为非法id则未找到
auto bucket_index = directory_page->HashToBucketIndex(hash);
auto bucket_page_id = directory_page->GetBucketPageId(bucket_index);
LOG_DEBUG("要获得的bucket_page_id是:%d,哈系数是%d", bucket_page_id, hash);
if (bucket_page_id == INVALID_PAGE_ID) {
return false;
}
ReadPageGuard bucket_guard = bpm_->FetchPageRead(bucket_page_id);
// 获取bucket_page
directory_guard.Drop();
auto bucket_page = bucket_guard.As>();// 在bucket_page上查找
V value;
if (bucket_page->Lookup(key, value, cmp_)) {
result->push_back(value);
return true;
}
return false;
}
2.4 Insert
2.4.1 详解 看图就行,注意拆分桶这里,拆分一次不一定就拆好了,可能一个还是满的,一个空的,所以还要回到insert方法,接着判断满没满。
2.4.2 代码
template
auto DiskExtendibleHashTable::Insert(const K &key, const V &value, Transaction *transaction) ->bool {
std::vectorvaluesFound;
bool keyExists = GetValue(key, &valuesFound, transaction);
if (keyExists) {
// 已存在直接返回false表示不插入重复键
return false;
}
auto hash_key = Hash(key);
// 获取header page
WritePageGuard header_guard = bpm_->FetchPageWrite(header_page_id_);
auto header_page = header_guard.AsMut();
// 使用header_page来获取目录索引
auto directory_index = header_page->HashToDirectoryIndex(hash_key);
//用目录索引获取目录页,然后找到頁的目录ID
page_id_t directory_page_id = header_page->GetDirectoryPageId(directory_index);
// 若dir_page_id为非法id则在新的dir_page添加
if (directory_page_id == INVALID_PAGE_ID) {
return InsertToNewDirectory(header_page, directory_index, hash_key, key, value);
}
// 对directory加锁
header_guard.Drop();
WritePageGuard directory_guard = bpm_->FetchPageWrite(directory_page_id);
// 获取 dir page
auto directory_page = directory_guard.AsMut();
// 通过hash值获取bucket_page_id。若bucket_page_id为非法id则在新的bucket_page添加
auto bucket_index = directory_page->HashToBucketIndex(hash_key);
auto bucket_page_id = directory_page->GetBucketPageId(bucket_index);
if (bucket_page_id == INVALID_PAGE_ID) {
return InsertToNewBucket(directory_page, bucket_index, key, value);
}
// 对bucket加锁
WritePageGuard bucket_guard = bpm_->FetchPageWrite(bucket_page_id);
auto bucket_page = bucket_guard.AsMut>();// LOG_DEBUG("要插入的bucket是:%d,哈希数是%d",bucket_page_id,hash_key);
// 获取bucket_page插入元素,如果插入失败则代表该bucket_page满了
if (bucket_page->Insert(key, value, cmp_)) {
LOG_DEBUG("Insert bucket %d Success!", bucket_page_id);
return true;
}
auto h = 1U << directory_page->GetGlobalDepth();
// 判断是否能添加度,不能则返回
if (directory_page->GetLocalDepth(bucket_index) == directory_page->GetGlobalDepth()) {
if (directory_page->GetGlobalDepth() >= directory_page->GetMaxDepth()) {
return false;
}
directory_page->IncrGlobalDepth();
// 需要更新目录页
for (uint32_t i = h; i < (1U << directory_page->GetGlobalDepth()); ++i) {
auto new_bucket_page_id = directory_page->GetBucketPageId(i - h);
auto new_local_depth = directory_page->GetLocalDepth(i - h);
directory_page->SetBucketPageId(i, new_bucket_page_id);
directory_page->SetLocalDepth(i, new_local_depth);
}
}
directory_page->IncrLocalDepth(bucket_index);
directory_page->IncrLocalDepth(bucket_index + h);
// 拆份bucket
if (!SplitBucket(directory_page, bucket_page, bucket_index)) {
return false;
}
bucket_guard.Drop();
directory_guard.Drop();
return Insert(key, value, transaction);
}
template
auto DiskExtendibleHashTable::InsertToNewDirectory(ExtendibleHTableHeaderPage *header, uint32_t directory_idx,
uint32_t hash, const K &key, const V &value) ->bool {
page_id_t directory_page_id = INVALID_PAGE_ID;
WritePageGuard directory_guard = bpm_->NewPageGuarded(&directory_page_id).UpgradeWrite();
auto directory_page = directory_guard.AsMut();
directory_page->Init(directory_max_depth_);
header->SetDirectoryPageId(directory_idx, directory_page_id);
uint32_t bucket_idx = directory_page->HashToBucketIndex(hash);
LOG_DEBUG("InsertToNewDirectory directory_page_id:%d", directory_page_id);
return InsertToNewBucket(directory_page, bucket_idx, key, value);
}
template
auto DiskExtendibleHashTable::InsertToNewBucket(ExtendibleHTableDirectoryPage *directory, uint32_t bucket_idx,
const K &key, const V &value) ->bool {
page_id_t bucket_page_id = INVALID_PAGE_ID;
WritePageGuard bucket_guard = bpm_->NewPageGuarded(&bucket_page_id).UpgradeWrite();
auto bucket_page = bucket_guard.AsMut>();bucket_page->Init(bucket_max_size_);
directory->SetBucketPageId(bucket_idx, bucket_page_id);
LOG_DEBUG("InsertToNewBucket bucket_page_id:%d", bucket_page_id);
return bucket_page->Insert(key, value, cmp_);
}
2.5 Update
2.5.1 详解 更新的代码我抄的。大概就是更新了目录?insert更新目录的时候压根没用这个方法,自己写了个。Remove的时候用了。 2.5.2 代码
void DiskExtendibleHashTable::UpdateDirectoryMapping(ExtendibleHTableDirectoryPage *directory,
uint32_t new_bucket_idx, page_id_t new_bucket_page_id,
uint32_t new_local_depth, uint32_t local_depth_mask) {
for (uint32_t i = 0; i < (1U << directory->GetGlobalDepth()); ++i) {
// 检查目录条目是否需要更新为指向新桶
// 如果目录项对应的是原桶
if (directory->GetBucketPageId(i) == directory->GetBucketPageId(new_bucket_idx)) {
if (i & local_depth_mask) {
// 如果这个目录项的在新局部深度位上的值为1,应该指向新桶
directory->SetBucketPageId(i, new_bucket_page_id);
directory->SetLocalDepth(i, new_local_depth);
} else {
// 否则,它仍然指向原桶,但其局部深度需要更新
directory->SetLocalDepth(i, new_local_depth);
}
}
}
}
2.6 SplitBucket
2.6.1 详解 具体逻辑在insert的图里已经说完了,这里只需要注意,把满桶里的内容放到容器里以后要把原本的满桶清空。 2.6.2 代码
template
auto DiskExtendibleHashTable::SplitBucket(ExtendibleHTableDirectoryPage *directory,
ExtendibleHTableBucketPage*bucket, uint32_t bucket_idx)
->bool {
// 创建新bucket_page
page_id_t split_page_id;
WritePageGuard split_bucket_guard = bpm_->NewPageGuarded(&split_page_id).UpgradeWrite();
if (split_page_id == INVALID_PAGE_ID) {
return false;
}
auto split_bucket = split_bucket_guard.AsMut>();split_bucket->Init(bucket_max_size_);
uint32_t split_idx = directory->GetSplitImageIndex(bucket_idx);
uint32_t local_depth = directory->GetLocalDepth(bucket_idx);
directory->SetBucketPageId(split_idx, split_page_id);
directory->SetLocalDepth(split_idx, local_depth);
LOG_DEBUG("Spilt bucket_page_id:%d", split_page_id);
// 将原来满的bucket_page拆分到两个page页中
page_id_t bucket_page_id = directory->GetBucketPageId(bucket_idx);
if (bucket_page_id == INVALID_PAGE_ID) {
return false;
}
// 先将原来的数据取出,放置在entries容器中
int size = bucket->Size();
std::list> entries;for (int i = 0; i < size; i++) {
entries.emplace_back(bucket->EntryAt(i));
}
// 清空bucket:size_ = 0
bucket->Clear();
// 分到两个bucket_page中
for (const auto &entry : entries) {
uint32_t target_idx = directory->HashToBucketIndex(Hash(entry.first));
page_id_t target_page_id = directory->GetBucketPageId(target_idx);
if (target_page_id == bucket_page_id) {
bucket->Insert(entry.first, entry.second, cmp_);
} else if (target_page_id == split_page_id) {
split_bucket->Insert(entry.first, entry.second, cmp_);
}
}
return true;
}
2.7 Remove
2.7.1 详解 图没画,先用个别人的顶上。和下面的代码不是对应的!!!但思路是一样的
merge的情况,我们首先讲清楚什么情况下需要merge 这个bucket的local depth不为0,且大于0,对应的Split Bucket的local depth相同,并且两个bucket其中有一个为空即可。 因此,我们在merge的过程中,即使该bucket不为空,但是对应的split bukcet可能为空,因此每次都需要对两个bucket进行检查: if (merge_local_depth != local_depth || (!check_bucket->IsEmpty() && !merge_bucket->IsEmpty())) { break; } 这个判断分支就是,如果两个bucket的depth不相等,或者是两个bucket的都不是空的,那么就中止 我们只要将两个bucket中其中非空的那个bucket的page拿来共用即可,将空的bucket的page进行drop和delete处理。 2.7.2 代码
template
auto DiskExtendibleHashTable::Remove(const K &key, Transaction *transaction) ->bool {
uint32_t hash = Hash(key);
WritePageGuard header_guard = bpm_->FetchPageWrite(header_page_id_);
auto header_page = header_guard.AsMut();
uint32_t directory_index = header_page->HashToDirectoryIndex(hash);
page_id_t directory_page_id = header_page->GetDirectoryPageId(directory_index);
if (directory_page_id == INVALID_PAGE_ID) {
return false;
}
header_guard.Drop();
WritePageGuard directory_guard = bpm_->FetchPageWrite(directory_page_id);
auto directory_page = directory_guard.AsMut();
uint32_t bucket_index = directory_page->HashToBucketIndex(hash);
page_id_t bucket_page_id = directory_page->GetBucketPageId(bucket_index);
if (bucket_page_id == INVALID_PAGE_ID) {
return false;
}
WritePageGuard bucket_guard = bpm_->FetchPageWrite(bucket_page_id);
auto bucket_page = bucket_guard.AsMut>();bool res = bucket_page->Remove(key, cmp_);
bucket_guard.Drop();
if (!res) {
return false;
}
auto check_page_id = bucket_page_id;
ReadPageGuard check_guard = bpm_->FetchPageRead(check_page_id);
auto check_page = reinterpret_cast*>(check_guard.GetData());
uint32_t local_depth = directory_page->GetLocalDepth(bucket_index);
uint32_t global_depth = directory_page->GetGlobalDepth();
while (local_depth > 0) {
// 获取要合并的桶的索引
uint32_t convert_mask = 1 << (local_depth - 1);
uint32_t merge_bucket_index = bucket_index ^ convert_mask; 拼多多帮助力入口
uint32_t merge_local_depth = directory_page->GetLocalDepth(merge_bucket_index);
page_id_t merge_page_id = directory_page->GetBucketPageId(merge_bucket_index);
ReadPageGuard merge_guard = bpm_->FetchPageRead(merge_page_id);
auto merge_page = reinterpret_cast*>(merge_guard.GetData());
if (merge_local_depth != local_depth || (!check_page->IsEmpty() && !merge_page->IsEmpty())) {
break;
}
if (check_page->IsEmpty()) {
bpm_->DeletePage(check_page_id);
check_page = merge_page;
check_page_id = merge_page_id;
check_guard = std::move(merge_guard);
} else {
bpm_->DeletePage(merge_page_id);
}
directory_page->DecrLocalDepth(bucket_index);
local_depth = directory_page->GetLocalDepth(bucket_index);
uint32_t local_depth_mask = directory_page->GetLocalDepthMask(bucket_index);
uint32_t mask_idx = bucket_index & local_depth_mask;
uint32_t update_count = 1 << (global_depth - local_depth);
for (uint32_t i = 0; i < update_count; ++i) {
uint32_t tmp_idx = (i << local_depth) + mask_idx;
UpdateDirectoryMapping(directory_page, tmp_idx, check_page_id, local_depth, 0);
}
}
while (directory_page->CanShrink()) {
directory_page->DecrGlobalDepth();
}
return true;
}
Task 4 Concurrency Control
使用ReadPageGuard和WritePageGuard保证线程安全。task3 已经实现了,什么没改就过了。
需要注意的点:
GrowShrinkTest:这个的缓冲池容量只有3,在 Insert 和 Remove 过程中,如果一个 PageGuard 已经不需要再使用了,可以提前手动 Drop 而不是等离开作用域再进行析构。我的建议是只要得到了directory_id就把header的解开。directory和bucket不急着解,运行不通过再加Drop();如果提交有:page4 not exist那就是drop早了,如果是:0000000000xread memory就是drop晚了。
通过截图 这个代码调的我想死,网上代码基本没有,快写完了才找到个。之前主要都是复制别人的,也不用怎么调,看懂了稍微改改就行,这个project直接给我当头一拳。本地测试也不全,不想自己写只能强行把线上网站当调试器用,主要卡住的还是内存的加锁释放,光通过GrowShrinkTest就差不多花了3天。改完了发现也不是很难,蒙着改肯定慢啊!另外代码写的极其粗糙,只能说是过了,性能是不存在的。改不动了,真的改不动了,等哪天变成大佬了再说吧。
参考文章 [1]https://blog.csdn.net/cpp_juruo/article/details/134859050?spm=1001.2014.3001.5506 (【CMU 15-445】Proj2 Hash Index) [2]https://blog.csdn.net/qq_58887972/article/details/137065392?spm=1001.2014.3001.5502(cmu15445 2023fall project2) [3]https://blog.csdn.net/p942005405/article/details/84644069(c++ 之 std::move 原理实现与用法总结) [4]https://zhuanlan.zhihu.com/p/679864158(CMU15-445 2023 Fall Project#2 - Extensible Hash Index) [5]https://zhuanlan.zhihu.com/p/622221722?utm_campaign=&utm_medium=social&utm_psn=1758461816148398080&utm_source=qq(CMU 15-445 P1 Extendible Hash Table 可扩展哈希详细理解) [6]https://blog.csdn.net/MarksSa/article/details/135646298?spm=1001.2014.3001.5502([15-445 fall 2023] P2代码解析) [7]https://zhuanlan.zhihu.com/p/686889091(CMU 15445 2023fall Project2) [8]https://zhuanlan.zhihu.com/p/690666760(CMU 15-445 Bustub 2023-Fall Project 2 Extendible Hash Index 思路分享) [9]https://zhuanlan.zhihu.com/p/664444839(CMU15-445(2023FALL)-Project#2: Extendible Hash Index)
推荐链接