Challenges OS

profilecustardo
challenge11.c

#include<stdio.h> #include<string.h> #include<pthread.h> #include<stdlib.h> #include<unistd.h> #define MAX 100 pthread_mutex_t the_mutex; pthread_cond_t condc, condp; int buffer = 0; void* producer(void *ptr) { int i; printf("\n Producer is executing"); for (i = 1; i <= MAX; i++) { pthread_mutex_lock(&the_mutex); while (buffer != 0) { pthread_cond_wait(&condp, &the_mutex); } buffer = i; pthread_cond_signal(&condc); pthread_mutex_unlock(&the_mutex); printf("\n producing %d", buffer); } pthread_exit(0); } void* consumer(void *ptr) { int i; printf("\n Consumer is executing"); for (i = 1; i <= MAX; i++) { pthread_mutex_lock(&the_mutex); while (buffer == 0) { printf("\n Waiting for producer..."); pthread_cond_wait(&condc, &the_mutex); } printf("\n consuming %d", buffer); buffer = 0; printf("\n Signaling producer..."); pthread_cond_signal(&condp); pthread_mutex_unlock(&the_mutex); } pthread_exit(0); } int main(int argc, char **argv) { pthread_t tid[2]; int err; if (pthread_mutex_init(&the_mutex, NULL) != 0) { printf("\n mutex init failed\n"); return 1; } pthread_cond_init(&condc, NULL); //This is new pthread_cond_init(&condp, NULL); //This is new err = pthread_create(&(tid[0]), NULL, &consumer, NULL); if (err != 0) { printf("\n Can't create thread :[%s]", strerror(err)); return 1; } else { printf("\n Consumer thread created successfully"); } err = pthread_create(&(tid[1]), NULL, &producer, NULL); if (err != 0) { printf("\n Can't create thread :[%s]", strerror(err)); return 1; } else { printf("\n Producer thread created successfully"); } pthread_join(tid[0], NULL); pthread_join(tid[1], NULL); pthread_mutex_destroy(&the_mutex); pthread_cond_destroy(&condc); pthread_cond_destroy(&condp); printf("\n End of program\n"); }