#include "headers.h"

Mutex::Mutex()
{
    m_fInitialized = FALSE;
}

HRESULT Mutex::Create(Mutex * * ppMutex)
{
    AssertOutPtr(ppMutex);

    HRESULT hr;
    BOOL fSuccess;
    DWORD error;
    Mutex * pMutex = NULL;

    pMutex = new Mutex();
    if (NULL == pMutex)
    {
        hr = E_OUTOFMEMORY;
        goto LError;
    }

    fSuccess = InitializeCriticalSectionAndSpinCount(&pMutex->m_criticalsection, 0);
    if (!fSuccess)
    {
        error = GetLastError();
        hr = HRESULT_FROM_WIN32(error);
        goto LError;
    }

    pMutex->m_fInitialized = true;
    *ppMutex = pMutex;
    pMutex = NULL;
    hr = S_OK;

LError:

    if (NULL != pMutex)
        delete pMutex;

    return hr;
}

Mutex::~Mutex()
{
    if (this->m_fInitialized)
        DeleteCriticalSection(&this->m_criticalsection);
}

void Mutex::Enter(void)
{
    EnterCriticalSection(&this->m_criticalsection);
}

void Mutex::Leave(void)
{
    LeaveCriticalSection(&this->m_criticalsection);
}