鎖異常的封裝,繼承與自定義的異常類即可。
struct YR_Lock_Exception : public YR_Exception
{
YR_Lock_Exception(const string& buffer) : YR_Exception(buffer){}
YR_Lock_Exception(const string& buffer, int err) : YR_Exception(buffer,err){}
~YR_Lock_Exception() throw() {}
};
Linux下有各種鎖機制,比如互斥鎖、讀寫鎖、自旋鎖等,我們可以使用模板類實現對鎖的封裝。
template <class T> //T爲鎖的類型
class YR_LockT
{
public:
//構造函數,構造時加鎖
YR_LockT(const T& mutex) : _mutex(mutex)
{
_mutex.lock();
_acquired = true;
}
//析構函數,析構時解鎖
~YR_LockT()
{
if(_acquired)
_mutex.unlock();
}
//上鎖,如果已經上鎖,則拋出異常
void acquire() const
{
if(_acquired)
throw YR_Lock_Exception("thread has locked!");
_mutex.lock();
_acquired = true;
}
//嘗試上鎖
bool tryAcquire() const
{
_acquired = _mutex.tryLock();
return _acquired;
}
//釋放鎖,如果沒有上鎖,拋出異常
void release() const
{
if (!_acquired)
{
throw YR_Lock_Exception("thread hasn't been locked!");
}
_mutex.unlock();
_acquired = false;
}
//是否已經上鎖
bool acquired() const
{
return _acquired;
}
protected:
//構造函數,用於鎖嘗試操作
TC_LockT(const T& mutex, bool) : _mutex(mutex)
{
_acquired = _mutex.tryLock();
}
private:
TC_LockT(const TC_LockT&);
TC_LockT& operator=(const TC_LockT&);
protected:
//鎖對象
const T& _mutex;
//是否已經上鎖
mutable bool _acquired;
};
嘗試上鎖類:
template <typename T>
class YR_TryLockT : public YR_LockT<T>
{
public:
YR_TryLockT(const T& mutex) : YR_LockT<T>(mutex, true)
{
}
};
空鎖,不做任何鎖動作
class YR_EmptyMutex
{
public:
/**
* @brief 寫鎖.
*
* @return int, 0 正確
*/
int lock() const {return 0;}
/**
* @brief 解寫鎖
*/
int unlock() const {return 0;}
/**
* @brief 嘗試解鎖.
*
* @return int, 0 正確
*/
bool trylock() const {return true;}
};
讀寫鎖讀鎖模板類
template <typename T>
class YR_RW_RLockT
{
public:
/**
* @brief 構造函數,構造時加鎖
*
* @param lock 鎖對象
*/
YR_RW_RLockT(T& lock)
: _rwLock(lock),_acquired(false)
{
_rwLock.ReadLock();
_acquired = true;
}
/**
* @brief 析構時解鎖
*/
~YR_RW_RLockT()
{
if (_acquired)
{
_rwLock.Unlock();
}
}
private:
/**
*鎖對象
*/
const T& _rwLock;
/**
* 是否已經上鎖
*/
mutable bool _acquired;
YR_RW_RLockT(const YR_RW_RLockT&);
YR_RW_RLockT& operator=(const YR_RW_RLockT&);
};
讀寫鎖寫鎖模板類:
template <typename T>
class YR_RW_WLockT
{
public:
/**
* @brief 構造函數,構造時枷鎖
*
* @param lock 鎖對象
*/
YR_RW_WLockT(T& lock)
: _rwLock(lock),_acquired(false)
{
_rwLock.WriteLock();
_acquired = true;
}
/**
* @brief 析構時解鎖
*/
~YR_RW_WLockT()
{
if(_acquired)
{
_rwLock.Unlock();
}
}
private:
/**
*鎖對象
*/
const T& _rwLock;
/**
* 是否已經上鎖
*/
mutable bool _acquired;
YR_RW_WLockT(const YR_RW_WLockT&);
YR_RW_WLockT& operator=(const YR_RW_WLockT&);
};
};