Click here to Skip to main content
15,895,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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:

C++
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:

C#
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
Posted

1 solution

Quote:
if (hr = WaitForSingleObject(hSemaphore, waitTime) != WAIT_OBJECT_0)

You probably meant
C++
if ( ( hr = WaitForSingleObject(hSemaphore, waitTime)) != WAIT_OBJECT_0)

You know == operator has higher precedence than = one.
 
Share this answer
 
Comments
Fabio Ottavi 11-Jun-14 5:25am    
I have been staring at the code for half an hour without seeing it.
Thanks for double checking.

Fabio

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900