samuelk71
samuelk71

Reputation: 311

producer and consumer with mutexes and pthreading

So I am having a little trouble with the producer and consumer problem with 2 threads and mutexes. What I am trying to do is have the producer fill an array with 10 1's. Then the consumer consumes each 1 and makes it a 0. This filling and emptying just repeats 10 times. Here is what I have so far but it gets stuck on the first cycle:

#include <stdio.h>
#include <pthread.h>
#define N 10

pthread_mutex_t mut;
pthread_cond_t condc,condp;
int queue[N];
int buffer;

void* prod() {
    int i;
    for(i = 0; i<10; i++) {
        pthread_mutex_lock(&mut);
        while(queue[N] != 0) {
            pthread_cond_wait(&condp, &mut);
        }
        int k = 0;
        for(k=0; k<10; k++) {
            queue[k] = 1;
        }

        pthread_cond_signal(&condc);
        pthread_mutex_unlock(&mut);
        printf("\nproduced\n");
    }
    pthread_exit(0);
}

void* cons() {
    int i;
    for(i = 0; i<10; i++) {
        pthread_mutex_lock(&mut);
        while(queue[N] == 0) {
            pthread_cond_wait(&condc, &mut);
        }
        int k = 0;
        for(k=0; k<10; k++) {
            queue[k] = 0;
        }
        pthread_cond_signal(&condp);
        pthread_mutex_unlock(&mut);
        printf("\nconsumed\n");
    }
    pthread_exit(0);
}

main() {
    pthread_t producer, consumer;
    pthread_mutex_init(&mut, 0);
    pthread_cond_init(&condc, 0);
    pthread_cond_init(&condp, 0);
    pthread_create(&consumer,NULL,&cons, NULL);
    pthread_create(&producer,NULL,&prod, NULL);
    pthread_join(producer,0);
    pthread_join(consumer,0);
    pthread_cond_destroy(&condc);
    pthread_cond_destroy(&condp);
    pthread_mutex_destroy(&mut);

    return 0;
}

Upvotes: 1

Views: 147

Answers (1)

David Schwartz
David Schwartz

Reputation: 182865

You don't initialize the members of queue to any particular value before you start reading them. Also, you read queue out of range -- it has ten values but you read the eleventh. Lastly, you are never changing the value you read -- you set the first ten values, which you never look at.

Upvotes: 2

Related Questions