Click here to Skip to main content
12,304,652 members (64,132 online)
Click here to Skip to main content
Add your own
alternative version

Stats

113.1K views
786 downloads
15 bookmarked
Posted

Advanced critical section

, 8 Jul 2002
Rate this:
Please Sign up or sign in to vote.
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

Share

About the Author

0xdeadbeef
Web Developer
Germany Germany
No Biography provided

You may also be interested in...

Comments and Discussions

 
QuestionCompile with errors ?? Pin
Martin Schneider9-Jul-02 22:12
memberMartin Schneider9-Jul-02 22:12 
AnswerRe: Compile with errors ?? Pin
0xdeadbeef9-Jul-02 23:41
member0xdeadbeef9-Jul-02 23:41 
GeneralRe: Compile with errors ?? Pin
Martin Schneider10-Jul-02 4:28
memberMartin Schneider10-Jul-02 4:28 
GeneralRace condition in unlock Pin
Tim Smith8-Jul-02 8:07
memberTim Smith8-Jul-02 8:07 
GeneralRe: Race condition in unlock Pin
Rama Krishna8-Jul-02 8:17
memberRama Krishna8-Jul-02 8:17 
GeneralRe: Race condition in unlock Pin
Tim Smith8-Jul-02 9:13
memberTim Smith8-Jul-02 9:13 
GeneralRe: Race condition in unlock Pin
William E. Kempf8-Jul-02 8:35
memberWilliam E. Kempf8-Jul-02 8:35 
GeneralRe: Race condition in unlock Pin
Tim Smith8-Jul-02 9:04
memberTim Smith8-Jul-02 9:04 
GeneralRe: Race condition in unlock Pin
Tim Smith8-Jul-02 9:15
memberTim Smith8-Jul-02 9:15 
GeneralRe: Race condition in unlock Pin
staceyw20-Jun-04 15:56
memberstaceyw20-Jun-04 15:56 
GeneralRe: Race condition in unlock Pin
staceyw20-Jun-04 16:07
memberstaceyw20-Jun-04 16:07 
GeneralUpdated Pin
0xdeadbeef8-Jul-02 2:02
member0xdeadbeef8-Jul-02 2:02 
GeneralNot thread safe Pin
Dalle8-Jul-02 0:23
memberDalle8-Jul-02 0:23 
GeneralRe: Not thread safe Pin
0xdeadbeef8-Jul-02 0:26
member0xdeadbeef8-Jul-02 0:26 
GeneralRe: Not thread safe Pin
Dalle8-Jul-02 0:29
memberDalle8-Jul-02 0:29 
GeneralRe: Not thread safe Pin
Iceman8-Jul-02 1:08
memberIceman8-Jul-02 1:08 
GeneralRe: Not thread safe Pin
Mikael Edlund8-Jul-02 1:29
memberMikael Edlund8-Jul-02 1:29 
GeneralRe: Not thread safe Pin
Dalle8-Jul-02 1:33
memberDalle8-Jul-02 1:33 
GeneralRe: Not thread safe Pin
Anonymous8-Jul-02 1:40
memberAnonymous8-Jul-02 1:40 
GeneralRe: Not thread safe Pin
Dalle8-Jul-02 2:11
memberDalle8-Jul-02 2:11 
GeneralRe: Not thread safe Pin
Iceman8-Jul-02 3:28
memberIceman8-Jul-02 3:28 
GeneralRe: Not thread safe Pin
Dalle8-Jul-02 9:02
memberDalle8-Jul-02 9:02 
GeneralRe: Not thread safe Pin
Iceman8-Jul-02 9:21
memberIceman8-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.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.160530.1 | Last Updated 9 Jul 2002
Article Copyright 2002 by 0xdeadbeef
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid