Click here to Skip to main content
15,879,683 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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.
Posted
Comments
Philippe Mori 20-Feb-12 20:31pm    
You should not need the count. If you need it then you should probably use something else than a semaphore and do yout own logic.

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.
 
Share this answer
 
Check out NtQuerySemaphore. Some extra info can be found here: http://stackoverflow.com/questions/2579536/semaphores-values[^]

Good luck!
 
Share this answer
 
v2
If you just want to check if a semaphore wait would block, then just call the wait function with timeout 0:

C++
//! 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;
}


EDIT: 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.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900