

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


#define N 10 int buffer[N]; int counter = 0, in = 0, out = 0, total = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t prod_cond = PTHREAD_COND_INITIALIZER; pthread_cond_t cons_cond = PTHREAD_COND_INITIALIZER;
void *producer(void *junk) { while(1) { pthread_mutex_lock(&mutex); if( counter == N ) pthread_cond_wait(&prod_cond, &mutex);
buffer[in] = total++; printf("Produced: %d\n", buffer[in]); in = (in + 1) % N; counter++;
if( counter == 1 ) pthread_cond_signal(&cons_cond);
pthread_mutex_unlock(&mutex); } }
void *consumer(void *junk) { while(1) { pthread_mutex_lock(&mutex);
if( counter == 0 ) pthread_cond_wait(&cons_cond, &mutex);
printf("Consumed: %d\n", buffer[out]); out = (out + 1) % N; counter‐‐;
if( counter == (N‐1) ) pthread_cond_signal(&prod_cond);
pthread_mutex_unlock(&mutex); } }