Search code examples
c++windowsapicritical-section

Is this code a working critical section wrapper class


I've actually got 2 questions, heres the first one.

Using the code I found at two different sites, I wrote those two critical section wrapper classes.

Is it going to work?

#ifndef CRITICALSECTION_H
#define CRITICALSECTION_H
#include "windows.h"



class CriticalSection{
    long m_nLockCount;
    long m_nThreadId;
    typedef CRITICAL_SECTION cs;
    cs m_tCS;
public:
    CriticalSection(){
        ::InitializeCriticalSection(&m_tCS);
        m_nLockCount = 0;
        m_nThreadId = 0;
    }
    ~CriticalSection(){ ::DeleteCriticalSection(&m_tCS); }
    void Enter(){ ::EnterCriticalSection(&m_tCS);  }
    void Leave(){  ::LeaveCriticalSection(&m_tCS); }
    void Try();
};


class LockSection{
    CriticalSection* m_pCS;
public:
    LockSection(CriticalSection* pCS){
        m_pCS = pCS;
        if(m_pCS)m_pCS->Enter();
    }
    ~LockSection(){
        if(m_pCS)m_pCS->Leave();
    }
}

/*

Safe class basic structure;

class SafeObj
{
     CriticalSection m_cs;

public:
    void SafeMethod()
    {
        LockSection myLock(&m_cs);
        //add code to implement the method ...

    }
};



*/
#endif

And the second question. While browsing here, I noticed that the author did not include

::Initialize , Delete , Enter , Leave critical sections . Aren't these needed for the class to work properly? Or am I missing something?


Solution

  • The LockSection class uses RAII to call Enter and Leave. When the object is created, the Enter is called. When the object is destroyed (by going out of scope) the Leave is called.

    Initialize and Delete are called by the CriticalSection class' constructor and destructor.

    Learn RAII, learn it well. It is your friend.