分类: C/C++
2008-11-18 20:43:16
/**
* SharedLock.h
* @Author Tu Yongce
* @Created 2008-11-17
* @Modified 2008-11-17
* @Version 0.1
*/
#ifndef SHARED_LOCK_H_INCLUDED
#define SHARED_LOCK_H_INCLUDED
#include <stdexcept>
#include <string>
#include "SharedMutex.h"
#include "Noncopyable.h"
// lock exception class
class LockError: public std::logic_error
{
public:
explicit LockError(const std::string &msg): std::logic_error(msg) {}
};
// shared policy
class SharedPolicy
{
private:
SharedMutex &m_mutex;
bool m_locked;
protected:
// disallow instantiation
SharedPolicy(SharedMutex &mutex): m_mutex(mutex), m_locked(false)
{
}
void LockWithNoChecking()
{
m_mutex.AcquireShared();
m_locked = true;
}
void UnlockWithNoChecking()
{
m_mutex.ReleaseShared();
m_locked = false;
}
bool OwnLock() const
{
return m_locked;
}
};
// exclusive policy
class ExclusivePolicy
{
private:
SharedMutex &m_mutex;
bool m_locked;
protected:
// disallow instantiation
ExclusivePolicy(SharedMutex &mutex): m_mutex(mutex), m_locked(false)
{
}
void LockWithNoChecking()
{
m_mutex.AcquireExclusive();
m_locked = true;
}
void UnlockWithNoChecking()
{
m_mutex.ReleaseExclusive();
m_locked = false;
}
bool OwnLock() const
{
return m_locked;
}
};
// shared lock
template <class LockPolicy>
class SharedLock
: private LockPolicy, private Noncopyable
{
public:
explicit SharedLock(SharedMutex &mutex, bool lock = true): LockPolicy(mutex)
{
if (lock) {
LockWithNoChecking();
}
}
~SharedLock()
{
if (OwnLock()) {
UnlockWithNoChecking();
}
}
void Lock()
{
if (OwnLock()) {
throw LockError("already owned the lock when called Lock()");
}
LockWithNoChecking();
}
void Unlock()
{
if (!OwnLock()) {
throw LockError("did NOT own the lock when called Unlock()");
}
UnlockWithNoChecking();
}
};
// read lock
typedef SharedLock<SharedPolicy> ReadLock;
// write lock
typedef SharedLock<ExclusivePolicy> WriteLock;
#endif // SHARED_LOCK_H_INCLUDED
源代码打包下载:
|