如何获得信号量计数? [英] How to get Semaphore Count?

查看:146
本文介绍了如何获得信号量计数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何方法或API可以获取信号量的计数?目的是在信号量计数等于MaximumCount且没有更多线程可以执行时使用SetEvent.

Is there any way or API to get the count of Semaphore? The purpose is to SetEvent if the Semaphore Count is equal to the MaximumCount and no more threads are there to execute.

推荐答案

我已经完成了Research and Search的工作,并且发现没有什么可以获取信号量的确切计数.它仅以此方式设计,并且没有发布任何API来知道等待和执行的确切线程数以及出现竞争状况的原因.
I have done my part of Research and Search and found out that there is nothing to get the exact count of Semaphores. It is designed like this only and no API is released to know the exact number of threads waiting and executing and released cause of Race Condition.


签出NtQuerySemaphore.一些额外的信息可以在这里找到: http://stackoverflow.com/questions/2579536/semaphores-values [ ^ ]

祝您好运!
Check out NtQuerySemaphore. Some extra info can be found here: http://stackoverflow.com/questions/2579536/semaphores-values[^]

Good luck!


如果您只想检查信号量等待是否会阻塞,则只需使用超时0调用wait函数:

If you just want to check if a semaphore wait would block, then just call the wait function with timeout 0:

//! waitForSemaphore sets this event before a potential blocking attempt
//! to aquire the semaphore.
extern HANDLE warnEventHandle;

//! The semaphore.
extern HANDLE mySemaphore;

//! Tries to aquire mySemaphore.
//! @param timeout Milliseconds to wait for semaphore.
//! @return true if semaphore was aquired.
bool waitForSemaphore( DWORD timeout )
{
  // TODO: Check for error return values from WaitForSingleObject.
  if(WAIT_TIMEOUT == WaitForSingleObject(mySemaphore, 0))
  {
    SetEvent(warnEventHandle);
    return (WAIT_OBJECT_O == WaitForSingleObject(mySemaphore, timeout));
  }
  return true;
}



稍微更改了示例.第一个版本将两次获取信号量.尽管如此,此代码仅是一个示例-在每次调用时都应正确检查WaitForSingleObject的返回值.



Changed the example a bit. The first version would aquire the semaphore twice. Still, this code is only an illustration - the return value from WaitForSingleObject should be checked properly on each call.


这篇关于如何获得信号量计数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆