#include #include #include #include "putNget.h" #define SUMSIZE 500 static int sum = 0; static pthread_cond_t slots_cond = PTHREAD_COND_INITIALIZER; static pthread_cond_t items_cond = PTHREAD_COND_INITIALIZER; static pthread_mutex_t slots_lock = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t items_lock = PTHREAD_MUTEX_INITIALIZER; static int items = 0; static int slots = 0; void *producer(void * arg1){ int i; for (i = 1; i <= SUMSIZE; i++) { /* acquire right to a slot */ pthread_mutex_lock(&slots_lock); while (!(slots > 0)) pthread_cond_wait (&slots_cond, &slots_lock); slots--; pthread_mutex_unlock(&slots_lock); put_item(i*i); /* release right to an item */ pthread_mutex_lock(&items_lock); items++; pthread_cond_signal(&items_cond); pthread_mutex_unlock(&items_lock); } pthread_exit(NULL); } void *consumer(void *arg2){ int myitem; int i; for (i = 1; i <= SUMSIZE; i++) { pthread_mutex_lock(&items_lock); while(!(items > 0)) pthread_cond_wait(&items_cond, &items_lock); items--; pthread_mutex_unlock(&items_lock); get_item(&myitem); sum += myitem; pthread_mutex_lock(&slots_lock); slots++; pthread_cond_signal(&slots_cond); pthread_mutex_unlock(&slots_lock); } pthread_exit(NULL); } int main(void){ pthread_t prodtid, constid; int i, total; slots = get_buffersize(); total = 0; for (i = 1; i <= SUMSIZE; i++) total += i*i; printf("The checksum is %d\n", total); if (pthread_create(&constid, NULL, consumer, NULL)){ perror("Could not create consumer"); exit(EXIT_FAILURE); } if (pthread_create(&prodtid, NULL, producer, NULL)){ perror("Could not create producer"); exit(EXIT_FAILURE); } pthread_join(prodtid, NULL); pthread_join(constid, NULL); printf("The threads produced the sum %d\n", sum); exit(EXIT_SUCCESS); }