Use semaphore for producer/consumer case...
Hi,
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);
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);
}I can get around this by using a mutex and a separate atomic_t 'count' variable, but it's more a workaround that a solution...
Thanks,
Stelian.
Signature · 4 lines
Stelian Pop <[email protected]> |------------- Ingénieur Informatique Libre --------------| | Alcôve - http://www.alcove.com - Tel: +33 1 49 22 68 00 | |----------- Alcôve, l'informatique est libre ------------|
Quoted 11 lines · Stelian Pop
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.
Quoted 9 lines
producer() {
/* One item produced */
up(&sem);
}
consumer() {
/* Let's wait for 10 items */
atomic_set(&sem->count, -10);Quoted 7 lines
/* 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 [email protected]
Mountain View, CA, USA. http://www.nrg.org/
MontaVista Software [email protected]
Quoted 4 lines · Nigel Gamble
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)
You're right that the DECLARE_MUTEX does not (entirely) do the job, but I set manually the value of sem->count:
Quoted 6 lines
Quoted 1 line
atomic_set(&sem->count, -10);Then consumer could be:
/* Wait for 10 items to be produced */ for (i = 0; i < 10; i++) down(&sem);
IMHO, this will not work, because the producer could be issuing more than one 'up(&sem)' at the time...
Stelian.
Signature · 4 lines
Stelian Pop <[email protected]> |------------- Ingénieur Informatique Libre --------------| | Alcôve - http://www.alcove.com - Tel: +33 1 49 22 68 00 | |----------- Alcôve, l'informatique est libre ------------|