NT_SYSTEM
NT_SYSTEM

Reputation: 377

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?

Upvotes: 1

Views: 2336

Answers (2)

David Heffernan
David Heffernan

Reputation: 612854

I'll answer the first question. The second question involves code at a different site and you should only ask one question at a time. Perhaps someone else will answer the second question.

The code you included will work correctly. The members m_nLockCount and m_nThreadId are unused and not needed. The Try() method has no implementation but you can just delete it

Personally I would raise an exception if m_pCS is not assigned. That's a clear error condition. Silently continuing and pretending that the resource is protected is an obvious danger.

Upvotes: 2

Starkey
Starkey

Reputation: 9781

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.

Upvotes: 2

Related Questions