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

[入库:2005年8月18日] [更新:2007年3月24日]

本文简介:选择自 tang1975 的 blog

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

本文关键:critial_section
  相关方案
Google
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top