CritSec.h 1.34 KB
Newer Older
wester committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
#pragma once

//////////////////////////////////////////////////////////////////////////
//  CritSec
//  Description: Wraps a critical section.
//////////////////////////////////////////////////////////////////////////

class CritSec
{
public:
    CRITICAL_SECTION m_criticalSection;
public:
    CritSec()
    {
        InitializeCriticalSectionEx(&m_criticalSection, 100, 0);
    }

    ~CritSec()
    {
        DeleteCriticalSection(&m_criticalSection);
    }

    _Acquires_lock_(m_criticalSection)
    void Lock()
    {
        EnterCriticalSection(&m_criticalSection);
    }

    _Releases_lock_(m_criticalSection)
    void Unlock()
    {
        LeaveCriticalSection(&m_criticalSection);
    }
};


//////////////////////////////////////////////////////////////////////////
//  AutoLock
//  Description: Provides automatic locking and unlocking of a
//               of a critical section.
//
//  Note: The AutoLock object must go out of scope before the CritSec.
//////////////////////////////////////////////////////////////////////////

class AutoLock
{
private:
    CritSec *m_pCriticalSection;
public:
    _Acquires_lock_(m_pCriticalSection)
    AutoLock(CritSec& crit)
    {
        m_pCriticalSection = &crit;
        m_pCriticalSection->Lock();
    }

    _Releases_lock_(m_pCriticalSection)
    ~AutoLock()
    {
        m_pCriticalSection->Unlock();
    }
};