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

王朝vc·作者佚名  2006-01-08
窄屏简体版  字體: |||超大  

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&);

};

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航