通過(guò)Batch Write來(lái)實(shí)現(xiàn)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對(duì)外暴露的寫(xiě)接口包括Put,Delete和Write,其中Write需要WriteBatch作為參數(shù),而Put和Delete首先就是將當(dāng)前的操作封裝到一個(gè)WriteBatch對(duì)象,并調(diào)用Write接口。
opt是寫(xiě)選項(xiàng),從上面代碼并沒(méi)有看出處理并發(fā)的邏輯,其實(shí)對(duì)于多線程的處理是在DBImpl::Write函數(shù)中完成
WriteBatch
每一個(gè)WriteBatch都是以一個(gè)固定長(zhǎng)度的頭部開(kāi)始,然后后面接著許多連續(xù)的記錄(插入或刪除操作)
固定頭部格式:
固定頭部共12字節(jié),其中前8字節(jié)為WriteBatch的序列號(hào)(也就是每個(gè)操作對(duì)應(yīng)的全局序列號(hào)),對(duì)應(yīng)rep_[0]到rep_[7],每次處理Batch中的記錄時(shí)才會(huì)更新,后四字節(jié)為當(dāng)前Batch中的記錄數(shù),對(duì)應(yīng)rep_[8]到rep_[11];
后面的記錄結(jié)構(gòu)為:
插入數(shù)據(jù)時(shí):type(kTypeValue、kTypeDeletion),Key_size,Key,Value_size,Value
刪除數(shù)據(jù)時(shí):type(kTypeValue、kTypeDeletion),Key_size,Key
WriteBatchInternal提供了一系列的靜態(tài)操作接口來(lái)對(duì)WriteBatch的接口進(jìn)行封裝,而不是直接操作WriteBatch的接口。
Design
Writer封裝WriteBatch
/*struct DBImpl::Writer {
*? WriteBatch* batch;
*? bool sync;
*? bool done;//該batch是否完成的標(biāo)志done
* port::CondVar cv;//信號(hào)量cv用于多線程的同步
*};
*
*/
Source Code Chinese Comments
https://github.com/cld378632668/leveldb_chinese_comments
Referrence
http://blog.csdn.net/weixin_36145588/article/details/78133260