Re: Use semaphore for producer/consumer case...

From: Nigel Gamble (nigel@nrg.org)
Date: Fri Mar 23 2001 - 18:52:54 EST


On Fri, 23 Mar 2001, Stelian Pop wrote:
> I want to use a semaphore for the classic producer/consumer case
> (put the consumer to wait until X items are produced, where X != 1).
>
> If X is 1, the semaphore is a simple MUTEX, ok.
>
> But if the consumer wants to wait for several items, it doesn't
> seem to work (or something is bad in my code).
>
> What is wrong in the following ?
>
> DECLARE_MUTEX(sem);

For the producer/consumer case, you want to initialize the semaphore to
0, not 1 which DECLARE_MUTEX(sem) does. So I would use

__DECLARE_SEMAPHORE_GENERIC(sem, 0)

The count is then the number of items produced but not yet consumed.

> producer() {
> /* One item produced */
> up(&sem);
> }
>
> consumer() {
> /* Let's wait for 10 items */
> atomic_set(&sem->count, -10);
>
> /* This starts the producers, they will call producer()
> some time in the future */
> start_producers();
>
> /* Wait for completion */
> down(&sem);
> }

Then consumer could be:

        consumer()
        {
                int i;

                start_producers();

                /* Wait for 10 items to be produced */
                for (i = 0; i < 10; i++)
                        down(&sem);
        }

Nigel Gamble nigel@nrg.org
Mountain View, CA, USA. http://www.nrg.org/

MontaVista Software nigel@mvista.com

-
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@vger.kernel.org
More majordomo info at http://vger.kernel.org/majordomo-info.html
Please read the FAQ at http://www.tux.org/lkml/



This archive was generated by hypermail 2b29 : Fri Mar 23 2001 - 21:00:22 EST