I'm using a Semaphore for a Consumer/Producer synchronization.
When the consumer needs to use a resource, it calls WaitForSingleObject on the resource counter semaphore.
The semaphore is implemented with a simple wrapper class:
CSyncroSemaphore::CSyncroSemaphore() {
hSemaphore = NULL;
}
void CSyncroSemaphore::Create(int maxCount)
{
hSemaphore = CreateSemaphore(NULL, 0, maxCount, NULL);
if (hSemaphore == NULL)
throw CStringException("Error createing semaphore:%08x", GetLastError());
}
CSyncroSemaphore::~CSyncroSemaphore(void)
{
CloseHandle(hSemaphore);
}
void CSyncroSemaphore::Release(int releaseCount,bool &overflow)
{
BOOL ris;
overflow=false;
if ((ris=ReleaseSemaphore(hSemaphore,releaseCount,nullptr))==FALSE) {
if (GetLastError() == ERROR_TOO_MANY_POSTS) {
overflow = true;
return;
}
throw CStringException("Error releasing semaphore:%08x", GetLastError());
}
}
void CSyncroSemaphore::Wait(int waitTime, bool &timeout)
{
timeout = false;
DWORD hr;
if (hr = WaitForSingleObject(hSemaphore, waitTime) != WAIT_OBJECT_0) {
if (hr == WAIT_TIMEOUT) {
timeout = true;
return;
}
throw CStringException("Error wiaitng for semaphore:%08x", hr);
}
}
The strangeness is that in the wait function I get a return value of 1 from WaitForSingleObject, with the meaning of Timeout Expired. GetLastError returns S_OK.
I changed my code to:
if (hr == WAIT_TIMEOUT || hr==1) {
timeout = true;
return;
}
And everything works fine.
According to MSDN a return value of 1 could only be interpreted as WAIT_OBJECT_1, but this seems not true.
Am I missing something?
Thanks in advance,
Fabio