问题描述
我正在使用信号量进行消费者/生产者同步。
当消费者需要使用资源时,它会在资源计数器信号量上调用WaitForSingleObject。
信号量用一个简单的包装类实现:
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);
}
}
奇怪的是,在wait函数中,我从WaitForSingleObject获得返回值1 ,具有Timeout Expired的含义。 GetLastError返回S_OK。
我将我的代码更改为:
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;
}
一切正常。
根据MSDN,返回值为1可以只被解释为WAIT_OBJECT_1,但这似乎不正确。
我错过了什么吗?
谢谢提前,
Fabio
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
推荐答案
if(hr = WaitForSingleObject(hSemaphore,waitTime)!= WAIT_OBJECT_0)
if (hr = WaitForSingleObject(hSemaphore, waitTime) != WAIT_OBJECT_0)
你可能意味着
You probably meant
if ( ( hr = WaitForSingleObject(hSemaphore, waitTime)) != WAIT_OBJECT_0)
你知道 = =
运算符的优先级高于 =
1。
You know ==
operator has higher precedence than =
one.
这篇关于Semaphore上的WaitForSingleObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!