[英]How do you get the current count from CSemaphore?
你不应该关心 - 这是一个信号量,而不是线程共享的计数器。
也就是说,您可能会滥用ReleaseSemaphore
API的lpPreviousCount
输出参数
BOOL WINAPI ReleaseSemaphore(
__in HANDLE hSemaphore,
__in LONG lReleaseCount,
__out_opt LPLONG lpPreviousCount
);
想法:
CSemaphore &mySemaphore = /*initialized from somewhere*/;
HANDLE hsem = (HANDLE) mySemaphore; // http://msdn.microsoft.com/en-us/library/f5zcch25.aspx
LONG peeked_count;
::ReleaseSemaphore(hsem, 1 /*can't be 0, sorry!*/, &peeked_count);
请注意,遗憾的是您必须实际释放信号量(lReleaseCount必须> 0)
这不容易实现。 如果你真的想这样做,我能想到的就是尝试尽可能多地手动锁定信号量,直到锁定失败,0超时,然后立即解锁。 您还必须记住最大计数。 例如,未经测试的代码:
int max_count = 5;
CSemaphore sem (max_count, max_count);
/*...*/
int count = 0;
while (sem.Lock (0))
++count;
for (int i = 0; i != count; ++i)
sem.Unlock(count);
std::cout << "the lock count is " << (max_count - count);
编辑:
看到sehe的解决方案后 ,我认为更好的解决方案是两者的结合:
int max_count = 5;
CSemaphore sem (max_count, max_count);
if (sem.Lock(0))
{
LONG peeked_count;
::ReleaseSemaphore(hsem, 1 /*can't be 0, sorry!*/, &peeked_count);
/* peeked_count has the count */
}
else
{
/* I do not think it is safe to release the semaphore even if just for debugging. */
/* max_count has the count */
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.