In the project to do C + + found, because used to C # lock () {} and Java Synchronize () {},windows with the critical zone, mutual exclusion, kernel events, signal volume used up not too accustomed, so intend to own in VC + + packaging a similar stuff. Encapsulation of this I decided to use a critical section to do, the final form is as follows:
synchronize(object)
{
//....无论此处是否发生异常,object都能被释放掉。和c#的lock一样。
}
Don't say much, start code. Define a mutex class first
class Mutex
{
public:
Mutex(void);
~Mutex(void);
void Lock();
void UnLock();
private:
CRITICAL_SECTION m_criticalSection;
};
Implemented as follows
Mutex.cpp file
#include "Mutex.h"
Mutex::Mutex(void)
{
InitializeCriticalSection(&m_criticalSection);
}
Mutex::~Mutex(void)
{
DeleteCriticalSection(&m_criticalSection);//保证对象被析构时候能够删除临界区
}
void Mutex::Lock()
{
EnterCriticalSection(&m_criticalSection);
}
void Mutex::UnLock()
{
LeaveCriticalSection(&m_criticalSection);
}
In writing a lock class to wrap
Header File File
//为了方便把头文件定义到了Mutex.h文件里面去了,修改Mutex.h如、//下:
#define synchronized(M) for(Lock M##_lock = M; M##_lock; M##_lock.SetUnlock())//这句话后面会用到
class Mutex
{
public:
Mutex(void);
~Mutex(void);
void Lock();
void UnLock();
private:
CRITICAL_SECTION m_criticalSection;
};
class Lock
{
public:
Lock(Mutex &mutex);
~Lock(void);
void SetUnlock();
operator bool () const;
private:
Mutex &m_mutex;
bool m_locked;
};
Implementation of the Lock class: Lock.cpp file
#include "Mutex.h"
Lock::Lock(Mutex &mutex): m_mutex(mutex), m_locked(true)
{
m_mutex.Lock();
}
Lock::~Lock(void)
{/*一定要在析构函数中解锁,因为不管发生什么,只要对象离开他的生命周期(即离开大括号),都会调用其析构函数*/
m_mutex.UnLock();
}
void Lock::SetUnlock()
{
m_locked = false;
}
Lock::operator bool() const
{
return m_locked;
}