Click here to Skip to main content
15,867,765 members
Articles / Mobile Apps
Article

Advanced critical section

Rate me:
Please Sign up or sign in to vote.
1.43/5 (4 votes)
8 Jul 2002 128.4K   824   16   23
Advanced critical section which features TryLock and timeouts

Introduction

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 Lock and Unlock an object (which a Win32 critical section provides too). But there are two features "normal" critical sections don't provide:

  • A Lock function which has an optional timeout
  • A TryLock function which is not available on Win9x/Me operating systems

Operations

You can either derive an object you want to synchronize from the CriticalSection or make a CriticalSection a member of an object. Whenever you enter code which needs to be protected call the Lock or TryLock function of the critical section.

Have a look at the code to see how it works:

// *******************************************************
// CriticalSection: Implements a critical section. 
// Provides a function similar to TryEnterCriticalSection 
// which is not available on Win9x/Me OSs
// *******************************************************
class CriticalSection  
{
public:
    // Construction/Destruction...
    CriticalSection();
    virtual ~CriticalSection();

    // Operations...
    // Locks this object. If another thread has ownership of 
    // this object the function waits
    //  until it's allowed to enter or the timeout elapses...
    inline bool Lock(const DWORD& dwMilliseconds = INFINITE)
    {
        if (::InterlockedCompareExchange(&m_lLockCount, 1, 0) == 0)
        {
            m_dwThreadID = ::GetCurrentThreadId();
            return true;
        }

        if (m_dwThreadID == ::GetCurrentThreadId())
        {
            ++m_lLockCount;
            return true;
        }

        if (::WaitForSingleObject(m_hEventUnlocked, 
            dwMilliseconds) == WAIT_OBJECT_0)
            return Lock(0);

        return false;
    }

    // Unlocks this object...
    inline void Unlock()
    {
        if (m_dwThreadID != ::GetCurrentThreadId())
            return;

        if (::InterlockedCompareExchange(&m_lLockCount, 0, 1) == 1)
        {
            m_dwThreadID = 0;
            ::PulseEvent(m_hEventUnlocked);
        }
        else
            --m_lLockCount;
    }

    // Tries to lock this object. 
    // If not applicable "false" is returns immediately...
    inline bool TryLock()
    {
        return Lock(0);
    }

private:
    // Internal data...
    DWORD m_dwThreadID;
    LONG m_lLockCount;
    HANDLE m_hEventUnlocked;

};

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 or www.codecommunity.com.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Germany Germany
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionCompile with errors ?? Pin
Schnemar9-Jul-02 22:12
Schnemar9-Jul-02 22:12 
AnswerRe: Compile with errors ?? Pin
0xdeadbeef9-Jul-02 23:41
0xdeadbeef9-Jul-02 23:41 
GeneralRe: Compile with errors ?? Pin
Schnemar10-Jul-02 4:28
Schnemar10-Jul-02 4:28 
GeneralRace condition in unlock Pin
Tim Smith8-Jul-02 8:07
Tim Smith8-Jul-02 8:07 
GeneralRe: Race condition in unlock Pin
Rama Krishna Vavilala8-Jul-02 8:17
Rama Krishna Vavilala8-Jul-02 8:17 
GeneralRe: Race condition in unlock Pin
Tim Smith8-Jul-02 9:13
Tim Smith8-Jul-02 9:13 
GeneralRe: Race condition in unlock Pin
William E. Kempf8-Jul-02 8:35
William E. Kempf8-Jul-02 8:35 
GeneralRe: Race condition in unlock Pin
Tim Smith8-Jul-02 9:04
Tim Smith8-Jul-02 9:04 
GeneralRe: Race condition in unlock Pin
Tim Smith8-Jul-02 9:15
Tim Smith8-Jul-02 9:15 
GeneralRe: Race condition in unlock Pin
staceyw20-Jun-04 15:56
staceyw20-Jun-04 15:56 
GeneralRe: Race condition in unlock Pin
staceyw20-Jun-04 16:07
staceyw20-Jun-04 16:07 
GeneralUpdated Pin
0xdeadbeef8-Jul-02 2:02
0xdeadbeef8-Jul-02 2:02 
GeneralNot thread safe Pin
Anders Dalvander8-Jul-02 0:23
Anders Dalvander8-Jul-02 0:23 
GeneralRe: Not thread safe Pin
0xdeadbeef8-Jul-02 0:26
0xdeadbeef8-Jul-02 0:26 
GeneralRe: Not thread safe Pin
Anders Dalvander8-Jul-02 0:29
Anders Dalvander8-Jul-02 0:29 
GeneralRe: Not thread safe Pin
Iceman8-Jul-02 1:08
Iceman8-Jul-02 1:08 
GeneralRe: Not thread safe Pin
Mikael Edlund8-Jul-02 1:29
Mikael Edlund8-Jul-02 1:29 
GeneralRe: Not thread safe Pin
Anders Dalvander8-Jul-02 1:33
Anders Dalvander8-Jul-02 1:33 
GeneralRe: Not thread safe Pin
8-Jul-02 1:40
suss8-Jul-02 1:40 
GeneralRe: Not thread safe Pin
Anders Dalvander8-Jul-02 2:11
Anders Dalvander8-Jul-02 2:11 
GeneralRe: Not thread safe Pin
Iceman8-Jul-02 3:28
Iceman8-Jul-02 3:28 
GeneralRe: Not thread safe Pin
Anders Dalvander8-Jul-02 9:02
Anders Dalvander8-Jul-02 9:02 
GeneralRe: Not thread safe Pin
Iceman8-Jul-02 9:21
Iceman8-Jul-02 9:21 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.