gsmaker
gsmaker

Reputation: 603

How to handle semaphore after WAIT_TIMEOUT

Currently I am working on a C++ Project where created a Semaphore using below API.

m_hSem = ::CreateSemaphore(NULL, 0, 1, NULL);

And checking signaling object for timeout using below API

if (::WaitForSingleObject(m_hSem, 3000) == WAIT_TIMEOUT)
{
    //Request time out
}

If timeout occurred then do I need to release the semaphore?

Upvotes: 1

Views: 1086

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 597101

If timeout occurred then do I need to Release the Semaphore?

No, because the wait did not successfully decrement the semaphore's counter, so do not release the semaphore to increment its counter. Call ReleaseSemaphore() only if WaitForSingleObject() returned WAIT_OBJECT_0.

From Microsoft's documentation on Semaphore Objects:

A semaphore object is a synchronization object that maintains a count between zero and a specified maximum value. The count is decremented each time a thread completes a wait for the semaphore object and incremented each time a thread releases the semaphore. When the count reaches zero, no more threads can successfully wait for the semaphore object state to become signaled. The state of a semaphore is set to signaled when its count is greater than zero, and nonsignaled when its count is zero.

...

Each time one of the wait functions returns because the state of a semaphore was set to signaled, the count of the semaphore is decreased by one. The ReleaseSemaphore function increases a semaphore's count by a specified amount.

Upvotes: 2

catnip
catnip

Reputation: 25388

If timeout occurred then do I need to Release the Semaphore?

No. The wait is deemed to have failed in this case.

The documentation is a little misleading in the way it is worded but the example code is clear enough.

Upvotes: 0

Related Questions