CSharedCriticalSection 实现临界区的访问:加锁、去锁
CSharedMutex 实现临时窃取临界区对象,然后加锁,对象销毁时又会去锁,然后归还对象
class CSharedCriticalSection {
public:
CSharedCriticalSection() {
InitializeCriticalSection(&critical_section_);
}
~CSharedCriticalSection() {
DeleteCriticalSection(&critical_section_);
}
void lock() {
EnterCriticalSection(&critical_section_);
}
void unlock() {
LeaveCriticalSection(&critical_section_);
}
private:
CRITICAL_SECTION critical_section_;
};
class CSharedMutex {
public:
explicit CSharedMutex(CSharedCriticalSection& critical_section)
: is_lock_(false)
, critical_section_(critical_section)
{
if(is_lock_ == false) {
is_lock_ = true;
critical_section_.lock();
}
}
~CSharedMutex(){
if(is_lock_) {
is_lock_ = false;
critical_section_.unlock();
}
}
void lock() {
if(is_lock_ == false) {
is_lock_ = true;
critical_section_.lock();
}
}
void unlock() {
if(is_lock_) {
is_lock_ = false;
critical_section_.unlock();
}
}
protected:
CSharedMutex(const CSharedMutex& rhs)
: critical_section_(rhs.critical_section_)
{
}
CSharedMutex& operator=(const CSharedMutex& rhs) {
return *this;
}
private:
volatile bool is_lock_;
CSharedCriticalSection& critical_section_;
};