通过Batch Write来实现Concurrent Write
Overview
Put与Delete操作
Status DB::Put(constWriteOptions& opt,constSlice& key,constSlice&value) {
WriteBatch batch;
batch.Put(key,value);returnWrite(opt, &batch);
}
Status DB::Delete(constWriteOptions& opt,constSlice& key) {
WriteBatch batch;
batch.Delete(key);returnWrite(opt, &batch);
}
LevelDB对外暴露的写接口包括Put,Delete和Write,其中Write需要WriteBatch作为参数,而Put和Delete首先就是将当前的操作封装到一个WriteBatch对象,并调用Write接口。
opt是写选项,从上面代码并没有看出处理并发的逻辑,其实对于多线程的处理是在DBImpl::Write函数中完成
WriteBatch
每一个WriteBatch都是以一个固定长度的头部开始,然后后面接着许多连续的记录(插入或删除操作)
固定头部格式:
固定头部共12字节,其中前8字节为WriteBatch的序列号(也就是每个操作对应的全局序列号),对应rep_[0]到rep_[7],每次处理Batch中的记录时才会更新,后四字节为当前Batch中的记录数,对应rep_[8]到rep_[11];
后面的记录结构为:
插入数据时:type(kTypeValue、kTypeDeletion),Key_size,Key,Value_size,Value
删除数据时:type(kTypeValue、kTypeDeletion),Key_size,Key
WriteBatchInternal提供了一系列的静态操作接口来对WriteBatch的接口进行封装,而不是直接操作WriteBatch的接口。
Design
Writer封装WriteBatch
/*struct DBImpl::Writer {
* WriteBatch* batch;
* bool sync;
* bool done;//该batch是否完成的标志done
* port::CondVar cv;//信号量cv用于多线程的同步
*};
*
*/
Source Code Chinese Comments
https://github.com/cld378632668/leveldb_chinese_comments
Referrence
http://blog.csdn.net/weixin_36145588/article/details/78133260