如何从 CSemaphore 获取当前计数?
我正在尝试调试使用 CSemaphore 限制缓冲区的大小。
如何从此类中获取信号量计数器的当前值?它似乎不能从它的任何成员直接访问,而且我似乎也找不到任何可以给我它的函数。
I am trying to debug a multi-threaded program that uses CSemaphore to limit the size of a buffer.
How do you get the current value of the semaphore counter from this class? It doesn't seem to be directly accessed from any of its members, and I can't seem to find any functions that will give me it either.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不应该关心 - 这是一个信号量,而不是线程共享计数器。
也就是说,您可能会滥用
ReleaseSemaphore
API 的lpPreviousCount
输出参数这个想法:
请注意,不幸的是您必须实际释放信号量(lReleaseCount 必须 >0)
You're not supposed to care - this is a semaphore, not thread-shared counter.
That said, you might abuse the
ReleaseSemaphore
API'slpPreviousCount
output parameterThe idea:
Note that unfortunately you'll have to actually release the semaphore (lReleaseCount must be >0)
这并不容易实现。如果你真的想这样做,我能想到的就是尝试尽可能多次手动锁定信号量,直到锁定失败,超时为0,然后立即解锁。您还必须记住最大计数。例如,未经测试的代码:
编辑:
看到sehe的解决方案,我认为更好的解决方案是两者的结合:
That is not easily possible. If you really want to do that, all I can think of doing is to try to lock the semaphore manually as many times as possible, until the locking fails, with 0 time-out, and unlocking immediately after that. You will also have to remember the max count. E.g., untested code:
EDIT:
After seeing sehe's solution, I think a better solution would be combination of both: