Reputation: 377
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
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
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