Listing F
// CriticalSection.h
 
 
#ifndef CRITICAL_SECTION___H
#define CRITICAL_SECTION___H
 
 
#include <windows.h>
 
 
class CCriticalSection
{
       // you are not allowed assign another object to this
       // we are talking about Critical Sections here
       CCriticalSection & operator = ( const CCriticalSection & Not_Implemented);
       CCriticalSection( const CCriticalSection & From);
 
 
public:
       CCriticalSection()
    { InitializeCriticalSection( GetCsPtr() ); }
 
 
    ~CCriticalSection()
    { DeleteCriticalSection( GetCsPtr() ); }
 
 
       void Lock()
    { EnterCriticalSection( GetCsPtr()); }
       void Unlock()
    { LeaveCriticalSection( GetCsPtr()); }
 
 
 
 
       operator LPCRITICAL_SECTION() const
    { return GetCsPtr(); }
 
 
private:
       LPCRITICAL_SECTION GetCsPtr() const
    { return &m_cs; }
 
 
private:
       // the critical section itself
    mutable CRITICAL_SECTION m_cs;
};
 
 
 
 
 
 
/*
 Description
      
       helper class
 
 
       allows automatic Locking/ Unlocking of a Resource,
       protected by a Critical Section:
       - locking when this object gets constructed
       - unlocking when this object is destructed
        (goes out of scope)
 
 
 Usage
 
 
       when you need protected access to a resource, do the following
       1. Create a Critical Section associated with the resource
       2. Embody the code accessing the resource in braces {}
       3. Construct an CAutoLockUnlock object
 
 
  Example:
       // we assume that m_CriticalSection
       // is a private variable, and we use it to protect
       // 'this' from being accessed while we need safe access to a resource
      
 
 
       // code that does not need resource locking
      
       {
              CAutoLockUnlock I_am_locked( m_cs);
             
              // code that needs thread locking
       }
      
       // code that does not need resource locking
 
 
*/
class CAutoLockUnlock
{
       CAutoLockUnlock operator=( CAutoLockUnlock & Not_Implemented);
       CAutoLockUnlock( const CAutoLockUnlock & Not_Implemented);
 
 
public:
       CAutoLockUnlock( CCriticalSection & csResource)
              : m_csResource( csResource)
       {
              m_csResource.Lock();
       }
 
 
       ~CAutoLockUnlock()
       {
              m_csResource.Unlock();
       }
 
 
private:
 
 
       // the Critical Section for this resource
       CCriticalSection & m_csResource;
};
 
 
 
 
#endif