Boost logo

Boost :

From: Alexander Terekhov (terekhov_at_[hidden])
Date: 2003-06-07 07:10:46


Stefan Seefeld wrote:
>
> Alexander Terekhov wrote:
>
> > Show me some code. I mean something that shows why do you need counting
> > semas.
>
> I'm using a bounded task queue (with the producer/consumer pattern),
> where the queue is implemented with std::queue, a mutex, and two semaphores.
> One semaphore counts the available tasks, the other the available slots
> for new tasks (as I said, the queue is bounded).

I see that you're also "not fond" of following the links. Okay.

<copy&paste>

This is far from elegant, because the queue data structure already knows the
number of messages either implicitly or with an extra counter of its own.
Usually, what is most relevant is whether or not the queue is empty.
So the semaphore is coding redundant information. Note that at times,
this information will be out of sync. For example, say you have
this sequence of actions:

    lock();
    append(item);
    unlock();
    signal(semaphore);

In between the append and signal operation, the queue has N+1 items,
but the semaphore's value is out of date at N.

A semaphore has an internal lock which protects incremnts and decrements
of its internal counter. There is no way to extend that lock to cover
additional data such as a queue. With a mutex and condition variable,
the entire queue can be treated as a semaphore based on its *own*
state!

So really, the samephore provides only a kludgy solution to synchronization
problems that are based on simple counting.

</copy&paste>

regards,
alexander.

--
http://google.com/groups?threadm=c29b5e33.0202011147.98b216e%40posting.google.com

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk