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&);
};
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&);
};
相关文章推荐
- C++算法系列之日历生成的算法代码
- ATL实现Connection Point的一种简单的方法
- 力争最简单把*、&说清楚
- 使用C#开发COM+组件
- 利用pre-compiled headers技术以加速编译速度--以Borland C++ Builder为例(四)
- 利用pre-compiled headers技术以加速编译速度--以Borland C++ Builder为例(二)
- 利用pre-compiled headers技术以加速编译速度--以Borland C++ Builder为例(一)
- 利用pre-compiled headers技术以加速编译速度--以Borland C++ Builder为例(五)
- 让应用程序禁止Windows屏幕保护
- 如何实现SDI与MDI的转换?
- LINUX中怎样限制不能使用FTP的用户
- InstallShield简明使用教程
- 注释与反注释Comment/Uncomment selected code in Visual C++
- 《C++中的动态多维数组》
- VC调试小技巧(菜鸟级)
- C++ Coding Tips - Chapter1
- 初学者看过来:简单谈谈 C/C++ 递归的思想,实现,以及和循环的关系。
- Generic Programming