临界区访问的两个类:临界区类,共享临界区类——多平台版本
/********************************************************
* @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;#elsetypedef pthread_mutex_t thread_mutex;#endif classUTILITY_API CThreadMutex final {public:
CThreadMutex() {
#ifdef WIN32
InitializeCriticalSection(&mutex_);#elsepthread_mutex_init(&mutex_, nullptr);#endif}~CThreadMutex(){
#ifdef WIN32
DeleteCriticalSection(&mutex_);#elsepthread_mutex_destroy(&mutex_);#endif}void lock() {
is_lock_= true;
#ifdef WIN32
EnterCriticalSection(&mutex_);#elsepthread_mutex_lock(&mutex);#endif}voidunlock(){
is_lock_= false;
#ifdef WIN32
LeaveCriticalSection(&mutex_);#elsepthread_mutex_unlock(&mutex_);#endif}bool islock()const{returnis_lock_;
}
thread_mutex* get(){return &mutex_;
}private:
thread_mutex mutex_;volatile boolis_lock_;
};classUTILITY_API CAutoThreadMutex final {public:explicit CAutoThreadMutex(CThreadMutex*mutex_ptr): mutex_(mutex_ptr) {lock();
}~CAutoThreadMutex() {
unlock();
}void lock() {if(mutex_){
mutex_->lock();
}
}voidunlock() {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