Implement ReadWrite locks for leveldb

Summary:
Implement ReadWrite locks for leveldb. These will be helpful
to implement a read-modify-write operation (e.g. atomic increments).

Test Plan: does not modify any existing code

Reviewers: heyongqiang

Reviewed By: heyongqiang

CC: MarkCallaghan

Differential Revision: https://reviews.facebook.net/D5787
This commit is contained in:
Dhruba Borthakur 2012-10-01 21:58:36 -07:00
parent fec81318b0
commit a58d48de79
3 changed files with 67 additions and 0 deletions

View File

@ -46,6 +46,16 @@ void CondVar::SignalAll() {
PthreadCall("broadcast", pthread_cond_broadcast(&cv_));
}
RWMutex::RWMutex() { PthreadCall("init mutex", pthread_rwlock_init(&mu_, NULL)); }
RWMutex::~RWMutex() { PthreadCall("destroy mutex", pthread_rwlock_destroy(&mu_)); }
void RWMutex::ReadLock() { PthreadCall("read lock", pthread_rwlock_rdlock(&mu_)); }
void RWMutex::WriteLock() { PthreadCall("write lock", pthread_rwlock_wrlock(&mu_)); }
void RWMutex::Unlock() { PthreadCall("unlock", pthread_rwlock_unlock(&mu_)); }
void InitOnce(OnceType* once, void (*initializer)()) {
PthreadCall("once", pthread_once(once, initializer));
}

View File

@ -97,6 +97,24 @@ class Mutex {
void operator=(const Mutex&);
};
class RWMutex {
public:
RWMutex();
~RWMutex();
void ReadLock();
void WriteLock();
void Unlock();
void AssertHeld() { }
private:
pthread_rwlock_t mu_; // the underlying platform mutex
// No copying allowed
RWMutex(const RWMutex&);
void operator=(const RWMutex&);
};
class CondVar {
public:
explicit CondVar(Mutex* mu);

View File

@ -33,6 +33,45 @@ class MutexLock {
void operator=(const MutexLock&);
};
//
// Acquire a ReadLock on the specified RWMutex.
// The Lock will be automatically released then the
// object goes out of scope.
//
class ReadLock {
public:
explicit ReadLock(port::RWMutex *mu) : mu_(mu) {
this->mu_->ReadLock();
}
~ReadLock() { this->mu_->Unlock(); }
private:
port::RWMutex *const mu_;
// No copying allowed
ReadLock(const ReadLock&);
void operator=(const ReadLock&);
};
//
// Acquire a WriteLock on the specified RWMutex.
// The Lock will be automatically released then the
// object goes out of scope.
//
class WriteLock {
public:
explicit WriteLock(port::RWMutex *mu) : mu_(mu) {
this->mu_->WriteLock();
}
~WriteLock() { this->mu_->Unlock(); }
private:
port::RWMutex *const mu_;
// No copying allowed
WriteLock(const WriteLock&);
void operator=(const WriteLock&);
};
} // namespace leveldb