通過Batch Write來實(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對外暴露的寫接口包括Put箱季,Delete和Write没炒,其中Write需要WriteBatch作為參數(shù),而Put和Delete首先就是將當(dāng)前的操作封裝到一個(gè)WriteBatch對象妥曲,并調(diào)用Write接口。
opt是寫選項(xiàng)当悔,從上面代碼并沒有看出處理并發(fā)的邏輯蚓曼,其實(shí)對于多線程的處理是在DBImpl::Write函數(shù)中完成
WriteBatch
每一個(gè)WriteBatch都是以一個(gè)固定長度的頭部開始,然后后面接著許多連續(xù)的記錄(插入或刪除操作)
固定頭部格式:
固定頭部共12字節(jié)沥割,其中前8字節(jié)為WriteBatch的序列號(hào)(也就是每個(gè)操作對應(yīng)的全局序列號(hào))耗啦,對應(yīng)rep_[0]到rep_[7],每次處理Batch中的記錄時(shí)才會(huì)更新机杜,后四字節(jié)為當(dāng)前Batch中的記錄數(shù)帜讲,對應(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)操作接口來對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