C++之MutexLock和MutexLockGuard封装
2021-03-25 18:25
标签:ati fine detach return head mes protect name define C++之MutexLock和MutexLockGuard封装 标签:ati fine detach return head mes protect name define 原文地址:https://www.cnblogs.com/ims-/p/13763612.html
noncopyable.h
#ifndef __WD_NONCOPYABLE_H__
#define __WD_NONCOPYABLE_H__
namespace wd
{
class Noncopyable
{
protected:
Noncopyable(){}
~Noncopyable(){}
private:
Noncopyable(const Noncopyable&);
Noncopyable & operator=(const Noncopyable &);
};
}//end of namespace wd
#endif
thread.h
#ifndef __WD_MUTEXLOCK_H__
#define __WD_MUTEXLOCK_H__
#include "Noncopyable.h"
#include
:public Noncopyable //表达语义
{
public:
MutexLock()
{ pthread_mutex_init(&_mutex, NULL); }
~MutexLock()
{ pthread_mutex_destroy(&_mutex); }
void lock()
{ pthread_mutex_lock(&_mutex);}
void unlock()
{ pthread_mutex_unlock(&_mutex);}
pthread_mutex_t * getMutexLockPtr()
{ return &_mutex; }
private:
pthread_mutex_t _mutex;
};
//RAII
class MutexLockGuard
{
public:
MutexLockGuard(MutexLock & mutex)
: _mutex(mutex)
{ _mutex.lock(); }
~MutexLockGuard()
{ _mutex.unlock(); }
private:
MutexLock & _mutex;
};
}//end of namespace wd
#endif
thread.cc
#include "Thread.h"
#include
test
#include "Thread.h"
#include
文章标题:C++之MutexLock和MutexLockGuard封装
文章链接:http://soscw.com/index.php/essay/67951.html