I had the need for a critical section which is easy to use and is independent of libraries like MFC.
Besides it should work on all Microsoft operating systems like Win9x/Me, WinNT/2K/XP and PocketPC/CE stuff.
So I wrote a class called
CriticalSection which fits my needs.
It implements functionality to
Unlock an object (which a Win32 critical section provides too).
But there are two features "normal" critical sections don't provide:
Lock function which has an optional timeout
TryLock function which is not available on Win9x/Me operating systems
You can either derive an object you want to synchronize from the
CriticalSection or make a
a member of an object. Whenever you enter code which needs to be protected call the
function of the critical section.
Have a look at the code to see how it works:
inline bool Lock(const DWORD& dwMilliseconds = INFINITE)
if (::InterlockedCompareExchange(&m_lLockCount, 1, 0) == 0)
m_dwThreadID = ::GetCurrentThreadId();
if (m_dwThreadID == ::GetCurrentThreadId())
dwMilliseconds) == WAIT_OBJECT_0)
inline void Unlock()
if (m_dwThreadID != ::GetCurrentThreadId())
if (::InterlockedCompareExchange(&m_lLockCount, 0, 1) == 1)
m_dwThreadID = 0;
inline bool TryLock()
The supplied sample application will show you how it works...
If you need help with this or have suggestions how to improve it
or state bugs feel free to drop me an email.
Updated versions may be found at www.nitrobit.com