繁体   English   中英

你如何从CSemaphore获得当前的数量?

[英]How do you get the current count from CSemaphore?

我正在尝试调试一个使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM