/********************************************************
* @file : Mutex.h
* @desc : 同步对象
* @author :
* @date : 2019-7-30
* @version : 1.0.0
*********************************************************/
#ifndef UTILITY_MUTEX_H_
#define UTILITY_MUTEX_H_
#include "UtilityDef.h"
#ifdef WIN32
typedef CRITICAL_SECTION thread_mutex;
#else
typedef pthread_mutex_t thread_mutex;
#endif
class UTILITY_API CThreadMutex final {
public:
CThreadMutex() {
#ifdef WIN32
InitializeCriticalSection(&mutex_);
#else
pthread_mutex_init(&mutex_, nullptr);
#endif
}
~CThreadMutex(){
#ifdef WIN32
DeleteCriticalSection(&mutex_);
#else
pthread_mutex_destroy(&mutex_);
#endif
}
void lock() {
is_lock_ = true;
#ifdef WIN32
EnterCriticalSection(&mutex_);
#else
pthread_mutex_lock(&mutex);
#endif
}
void unlock(){
is_lock_ = false;
#ifdef WIN32
LeaveCriticalSection(&mutex_);
#else
pthread_mutex_unlock(&mutex_);
#endif
}
bool islock()const {
return is_lock_;
}
thread_mutex* get(){
return &mutex_;
}
private:
thread_mutex mutex_;
volatile bool is_lock_;
};
class UTILITY_API CAutoThreadMutex final {
public:
explicit CAutoThreadMutex(CThreadMutex* mutex_ptr): mutex_(mutex_ptr) {
lock();
}
~CAutoThreadMutex() {
unlock();
}
void lock() {
if(mutex_){
mutex_->lock();
}
}
void unlock() {
if(mutex_ && mutex_->islock()) {
mutex_->unlock();
}
}
thread_mutex* get() {
return mutex_->get();
}
protected:
CAutoThreadMutex(const CAutoThreadMutex& rhs) {
mutex_ = rhs.mutex_;
lock();
}
CAutoThreadMutex& operator=(const CAutoThreadMutex& rhs){
if(this == &rhs){
return *this;
}
mutex_ = rhs.mutex_;
return *this;
}
private:
CThreadMutex* mutex_;
};
#endif