A c++ class wrapper to simplify the use of CRITICAL_SECTION and avoid dead-lock

时间:2023-01-12 08:21:50

The first class is a simple wrapper of CRITICAL_SECTION. The second class provides a scoped lock. Even an exception occurs, the destructor of CGuard can automatically release the lock.

static CThreadMutext g_lockSomething;

// a function that want to access some thing

...

CGuard<CThreadMutext> guard(lockSomething);

 

// A c++ class wrapper to simplify the use of CRITICAL_SECTION
class CThreadMutex
{
public:
 CThreadMutex()
 {
  ::InitializeCriticalSection(&m_cs);
 }
 ~CThreadMutex()
 {
  ::DeleteCriticalSection(&m_cs);
 }
 void Enter() const
 {
  ::EnterCriticalSection((LPCRITICAL_SECTION)&m_cs);
 }
 void Leave() const
 {
  ::LeaveCriticalSection((LPCRITICAL_SECTION)&m_cs);
 }

#if(_WIN32_WINNT >= 0x0400)
 BOOL TryEnter() const
 {
  return ::TryEnterCriticalSection((LPCRITICAL_SECTION)&m_cs);
 }
#endif /* _WIN32_WINNT >= 0x0400 */

private:
 CRITICAL_SECTION m_cs;

 HIDDEN_COPY(CThreadMutex);
 MEM_LEAK_DETECT;
};

// Gurad class that use stack to autoly perform lock and unloack action
template <class MUTEX>
class CGuard
{
public:
 CGuard(const MUTEX& mutex)
  :m_oMutex(mutex)
 {
  m_oMutex.Enter();
 }
 ~CGuard()
 {
  m_oMutex.Leave();
 }
private:
 const MUTEX& m_oMutex;
 CGuard(const CGuard&);
 CGuard& operator = (const CGuard&);
};