jeudi 21 juillet 2016

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.

Aucun commentaire:

Enregistrer un commentaire