PlayHardGoPro
PlayHardGoPro

Reputation: 2933

Working with Producer and Consumer, sempahore in C

I'm trying to make a producer/ consumer application. The problem is, my producer is fillin the whole buffer THEN the consumer is removing the whole buffer... wasn't the consumer supposed to remove an item from the buffer as soon as the producer make a post to the semaphore ?

my code:

void* producerFunc(void* arg)
{
    while(n_insertions < N_PRODUCTS)
    {
        sem_wait(&sem_postAvaliable);
        sem_wait(&mutex);
        //Insert Item
        sem_post(&mutex);
        sem_post(&sem_posTaken);
    }
    pthread_exit(NULL);
}

void* consumerFunc(void* arg)
{
    while(n_consumed < N_PRODUCTS)
    {
        sem_wait(&sem_posTaken);
        sem_wait(&mutex);
        //Remove from bufer
        sem_post(&mutex);
        sem_post(&sem_postAvaliable);
    }
    pthread_exit(NULL);
}  

n_insertionsis a global integer that counts the number of items inserted into the buffer;

n_consumed is a global integer that counts the number of times the consumer consumed an item from the buffer.

Upvotes: 1

Views: 372

Answers (1)

Patricio S
Patricio S

Reputation: 2130

At a very high level, when you do a sem_post(&sem_posTaken) you are telling the consumers "Hey!, you can consume something", but after that depending on the processor scheduler the producers may continue producing until the counter of the semaphore doesn't allow them, so maybe a consumer consume right after the producer insert something or maybe after 3 inserts, who knows? The thread is blocked when you try to make a sem_wait of a semaphore whose counter is 0.

If you want to alternate between an insert and a remove, try initializing sem_postAvaliable to 1, that way you would allowing only one insertion at first, because the other threads would be blocked waiting a sem_post(&sem_postAvaliable), then only one consumer could consume whatever you inserted in the buffer and so on, but note that in this case a buffer with size larger than 1 would be meaningless.

Upvotes: 3

Related Questions