互斥锁常用方式

互斥锁常用方式:

(1)互斥锁nMutex 

(2)自动互斥锁 auto_mutex_lock(互斥锁nMutex的封装)

(3)元编程互斥锁bool_mutex


互斥锁继承不可复制类

不可复制类:

常作为父类实现对象的不可复制,其实就是私有化拷贝复制函数和赋值函数,连实现都不需要,因为在代码中是不会出现的,所以不需要链接源代码。这里构造函数和析构函数是保护的,觉得其实不需要也可以,因为也用不到noncopyable的什么成员,所以可以是以私有方式来继承。

class noncopyable
{
    protected:
        noncopyable() {}
        ~noncopyable() {}


    private:  // emphasize the following members are private
        noncopyable( const noncopyable& );
        const noncopyable& operator=( const noncopyable& );
};  


互斥锁:

/**
 * \author cjy
 * \description 互斥锁
 */
class nMutex : private noncopyable
{
public:
friend class thread_cond;
/**
* \author cjy
* \description锁类型枚举
*/
enum MutexType
{
fast = PTHREAD_MUTEX_ADAPTIVE_NP,//for "fast" mutexes
recursive = PTHREAD_MUTEX_RECURSIVE_NP,//for "recursive" mutexes
timed = PTHREAD_MUTEX_TIMED_NP,//for "timed" mutexes
errorcheck = PTHREAD_MUTEX_ERRORCHECK_NP//for "error checking" mutexes
};


/**
* \author cjy
* \description构造函数,构造一个互斥体对象
* \param _t 锁的类型MutexType
* \return 
*/
nMutex(MutexType _t = fast) 
{
pthread_mutexattr_t attr;
::pthread_mutexattr_init(&attr);
::pthread_mutexattr_settype(&attr, _t);
::pthread_mutex_init(&mutex, &attr);
}


/**
* \author cjy
* \description析构函数,销毁一个互斥体对象
*/
~nMutex() { ::pthread_mutex_destroy(&mutex); }

/**
* \author cjy
* \description加锁一个互斥体
*/
void lock() { ::pthread_mutex_lock(&mutex); }

/**
* \author cjy
* \description解锁一个互斥体
*/
void unlock() { ::pthread_mutex_unlock(&mutex); }

/**
* \description   试图加锁一个互斥体
* \author  cjy
* \return  true加锁成功
* false加锁失败(已经被其他线程锁住)
*/
bool trylock() { return (::pthread_mutex_trylock(&mutex) == 0); }
private:
/**
* \author cjy
* \description系统互斥体
*/
pthread_mutex_t mutex;
};


自动互斥锁:

/**
 * \author cjy
 * \description Wrapper
 * 方便在复杂函数中锁的使用
 */
class auto_mutex_lock : private noncopyable
{
public:
/**
* \author cjy
* \description 构造函数
* 对锁进行lock操作
* \param m 锁的引用
*/
auto_mutex_lock(nMutex &m) : mlock(m) { mlock.lock(); }
/**
* \author cjy
* \description 析购函数
* 对锁进行unlock操作
*/
~auto_mutex_lock() { mlock.unlock(); }
private:
/**
* \author cjy
* \description 锁的引用
*/
nMutex &mlock;
};



元编程互斥锁,有特化模板的锁和一般模板的锁。
/**
 * \author cjy
 * \description 定义一个锁的模版
 */
template <bool locker = true>
class bool_mutex
{
public:
/**
* \author cjy
* \description加锁操作
*/
void add_lock() { _lock.lock(); }
/**
* \author cjy
* \description解锁操作
*/
void free_lock() {_lock.unlock(); }
private:
nMutex _lock;
};


/**
 * \author cjy
 * \description 特化锁的模版
 */
template <>
class bool_mutex<false>
{
public:
/**
* \author cjy
* \description加锁操作
* 这里是空函数
*/
void add_lock() { }
/**
* \author cjy
* \description解锁操作
* 这里是空函数
*/
void free_lock() { }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值