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