CSDN博客

img tang1975

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

发表于2002/4/22 9:32:00  460人阅读

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

0 0

相关博文

我的热门文章

img
取 消
img