Intel® Moderncode for Parallel Architectures
Support for developing parallel programming applications on Intel® Architecture.

fast semaphores w/ timeout

jseigh2
Beginner
878 Views
It's possible to create a fast semaphore in same way that Critical Section is a fast Mutex on windows systems. Ok, not the same way exactly. Details are here. If you put it into production, I'd clean it up a little. Any non successful wait should be taken as a wait fail/timeout/cancel so the check of the return code from WaitForSingleObject should be changed from == WAIT_TIMEOUT to != WAIT_OBJECT_0, and it could use some argument validity checking.

You could also apply this to POSIX semaphores a long as you had compare and swap or the equivalent.

Joe Seigh
0 Kudos
3 Replies
Intel_C_Intel
Employee
878 Views
Its a very nice algo.
0 Kudos
ClayB
New Contributor I
878 Views
Joe -

Yes, that is a very slick implementation.

But, for any readers out there that may still think a semaphore is something used by the Navy to signal between ships, let me see if I understand a few of the details of your algorithm. When reading someone else's code, especially something this tight and elegant, I sometimes focus too much and miss the point, so tell me if I get anything wrong in the following description.

The count member is the actual number of threads that can "hold" the semaphore (qsem) at the current time. If the count is decremented to a negative number, the thread must wait on the semaphore. Should a sufficient time interval pass without the semaphore being available, the thread will "cancel" the request and move on.

When a thread finishes its use of the semaphore by calling the post function, this thread bumps up the count member by the number of cancel notices that have been given (a little light bookkeeping). Then, if the incremented count is zero or negative, the hSem is signaled and a waiting thread will not time out.

Is that about it?

-- clay
0 Kudos
Intel_C_Intel
Employee
878 Views
> The count member is the actual number of threads that
> can "hold" the semaphore (qsem) at the current time.

Yep.

> If the count is decremented to a negative number,
> the thread must wait on the semaphore.

Yes.

> Should a
> sufficient time interval pass without the semaphore
> being available, the thread will "cancel" the
> request and move on.

Yes.


> When a thread finishes its use of the semaphore by
> calling the post function, this thread bumps up the
> count member by the number of cancel notices that
> have been given (a little light bookkeeping).

This is the elegant part!

> Then,
> if the incremented count is zero or negative, the
> hSem is signaled and a waiting thread will not time
> out.
>
> Is that about it?

You got it.

0 Kudos
Reply