Re: Glib Semaphores



On Mon, 22 Nov 1999, Karl Nelson wrote:

> On addition of GSemaphore:
> 
> We seem not to have a conclusion to this yet.  One person 
> said great idea, one concludes horrible.  
> 
> I don't agree that join is equal to semaphores.  That is 
> only true in the limited case of threads which terminate
> imediately.  When doing some computation work like filtering
> in semaphores may be used for check pointing prior to a thread
> terminating.  But I doubt that Kaz Kylheku and I will ever
> agree on this point.  
> 
> Does everyone agree with Kaz's opinion?  If so I won't 
> bring up the issue again, but I just want to be sure.  

You can make a binary semaphore very easily using mutexes and conditions.  Just
protect a binary flag with a mutex, and then your up and down operations (or
signal and wait, or v and p) are just:

	semaphore::up()
	{
	    mutex.lock();
	    flag = true;
	    mutex.unlock();
	    cond.signal();
	}

	semaphore::down()
	{
	    mutex.lock();
	    while (!flag)
		cond.wait(mutex);
	    mutex.unlock();
	}

A counting semaphore can be dome similarly, just replace the flag with
a counter. This one assumes that the counter varies between zero and
some per-object configured maximum.

	semaphore::up()
	{
	    mutex.lock();
	    old = counter;
	    if (counter < maximum)
		counter++;
	    mutex.unlock();

	    if (old == 0)
		cond.signal(); // signal only on transition from 0
	}

	semaphore::down()
	{
	    mutex.lock();
	    while (counter == 0)
		cond.wait(mutex);
	    counter--;
	    mutex.unlock();
	}


This is probably less efficient than a carefully coded semaphore implemented
using lower level primitives, which will be different on each supported
platform. Such an implementation could, for example, use atomic operations to
update the counter or flag instead of relying on a mutex. There is no
standard API for such operations.

For a challenge, try implementing mutexes and conditions using only semaphores.
Don't forget the condition broadcast operation! ;)



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]