//************************************************************
//Semaphore
//************************************************************
#include "stdafx.h"
#include "semaphore.h"

Semaphore::Semaphore(LONG Maximum,LONG InitialCount)
{
    Count=0;
    hSemaphore[0] = CreateSemaphore(NULL,InitialCount,Maximum,NULL);
}

Semaphore::~Semaphore()
{
    CloseHandle(hSemaphore[0]);
}

BOOL Semaphore::Acquire(int Timeout,HANDLE hEvent)
{
    if(hEvent)
    {
        hSemaphore[1]=hEvent;
        DWORD Result=WaitForMultipleObjects(2,hSemaphore,FALSE,Timeout);
        if(Result==WAIT_TIMEOUT)
            Count=0;
        return (Result==WAIT_OBJECT_0);
    }
    else
    {
        DWORD Result=WaitForSingleObject(hSemaphore[0],Timeout);
        if(Result==WAIT_TIMEOUT)
            Count=0;
        return (Result==WAIT_OBJECT_0);
    }
}

BOOL Semaphore::Release()
{
    LONG NewCount;
    BOOL Result=ReleaseSemaphore(hSemaphore[0],1,&NewCount);
    Count=NewCount;
    return Result;
}
