Algorithms
Electronics
File Formats
Freeware
Games Programming
Hardware/Architecture
HTML/CCS & Java/Javascript
Humour
Link Site,Library
Linux,GNU,Unix
Magazines/Books
Network Protocols
Networks
New/Latest Stuff
Programming Languages
Servers/ISAPI/ IO Completion Ports
Sound/Music and Multimedia
Source Code
Visual Basic
Windows
Winsock

A Safer CRITICAL_SECTION

The code shown below encapsulates a Critical Section as used in Windows. These 2 objects make it so that even if you forget to "Leave the critical section the code will do it automatically. This is acompliced by the use of 2 classes. The first class called CriticalSection is the actual Critical Section. There other class called AutoSection is the part that makes this trick neat. An AutoSection Object is created whenever the code wants to own the CriticalSection. When the AutoSection Object goes out of scope and Destroyed, the CriticalSection object is automatically released for other threads to use.

class CriticalSection
{
public:
     CriticalSection(){InitializeCriticalSecion(&cs);}
     ~CriticalSection(){DeleteCriticalSection(&cs);}
     lock(){EnterCriticalSection(&cs);}
     unlock(){LeaveCriticalSection(&cs);}
protected:
    CRITICAL_SECTION cs;
};

class AutoSection
{
public:
    AutoSection(CriticalSection *pcs);
   ~AutoSection();
   lock();
   unlock();
protected:
  int acquiredCount;  // make sure you unlock it when you destroy the object
  CriticalSection *cs;
};
AutoSection::AutoSection(CriticalSection *pcs)
{
cs = pcs;
if(cs!=NULL) cs->lock();
}

AutoSection::~AutoSection()
{
if(cs!=NULL) cs->lock();
}

Example Usage

void ThreadMain(void *p)
{
CriticalSection cs = *p;  //Not very safe if NULL passed in
AutoSection section(cs);
// DoWork Here
}// Critical Section automatically released here

int main()
{
CriticalSection cs;
StartThread(&cs);
StartThread(&cs);
}

Copyright Geoffrey Smith 2000-2001