From: Rob McCool <robm@netscape.com>
Newsgroups: netscape.devs-nsapi,netscape.devs-server-technical
Subject: Re: Question about condition variable, critical section & Semaphore
Date: Fri, 26 Jul 1996 19:59:13 -0700

Satish Krishnaraj wrote: > how can I initialize a semaphore (sem_*) with a count. > Or better yet, I can do in Solaris 2.4 thread package. Using > NSAPI, how can I mimic that feature. We need that feature > in our extension(s). > If it cannot be done, isn't it an important feature. Without > which I think the thread related API of NSAPI is incomplete. > If so, how can it be done?

The reason a counting semaphore is not provided is that POSIX.4 does not provide it. I am reasonably certain that you could emulate the functionality using a critical section, an integer count, and a condition variable for making threads sleep and wake up, but I'd have to take some time thinking about it to make sure I got it right before I gave you any pseudocode. I do believe that the primitives provided are sufficient to build counting semaphores.

> Assume the following: > 1) condvar_notify(...) is invoked by thread 1 on Condition 1. > 2) condvar_wait(...) is invoked by thread 2 on condition 1. > > if condvar_wait(...) is invoked by thread 2 BEFORE > the invocation of condvar_notify() by thread 1 > (both on same condition 1), then there is no problem. > If condvar_wait(...) is invoked by thread 2 AFTER > the invocation of condvar_notify() by thread 1 > (both on same condition 1), then the notification is lost, > and thread 2 blocks forever.

Yes, this is one of the semantics of POSIX (and Solaris) condition variables. When testing the condition which says that you must call condvar_wait(), you must also be holding the critical section associated with the condition variable.

If you used an integer count, and protected access to the condvar and the integer count using the critical section, then what you may want to do is "block if count < 0, decrement the count and release the critical section otherwise". Off the top of my head this would provide counting semaphore semantics, but again my memory be a bit rusty.

> Is my assumtion that NSAPI does not have the count semantics in > semaphores correct?

The sem_* routines, yes.

--
Rob McCool, robm@netscape.com http://home.netscape.com/people/robm/
Stunt Programmer, Netscape Communications Corporation
It was working ten minutes ago, I swear...
Reproduced by permission of the author.