您的位置:首页 > 移动开发

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

2002-04-22 09:32 656 查看
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&);
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息