/* Program to demo producer-consumer problem. */ /* Usage: cc -o burger burger.c -pthread */ /* ./burger */ /* Written by Carey Williamson, Feb 24/2010 */ /* This version uses three threads of control: */ /* - main thread creates two child threads */ /* - "chef" produces new hamburgers */ /* - "customer" eats hamburgers */ #include #include #define NUM_BURGERS 20 #define MAX_BURGER_PILE 5 #define MAX_PRODUCER_NAP_DURATION 10 #define MAX_CONSUMER_NAP_DURATION 10 /* global variable shared by all threads */ int burgerpile; void *chef(); /* the thread for producer */ void *customer(); /* the thread for consumer */ /* Mutual exclusion (mutex) locks for thread coordination */ pthread_mutex_t counter; int main(int argc, char *argv[]) { pthread_t tid1, tid2; /* thread identifiers */ pthread_attr_t attr; /* set of thread attributes */ int i; /* Initialize */ burgerpile = 0; pthread_mutex_init(&counter, NULL); /* get the default attributes */ pthread_attr_init(&attr); /* create the producer thread */ pthread_create(&tid1, &attr, chef, NULL); /* create the consumer thread */ pthread_create(&tid2, &attr, customer, NULL); /* wait for the chef to exit */ pthread_join(tid1, NULL); /* wait for the customer to exit */ pthread_join(tid2, NULL); /* output the final result */ printf("All done, folks!\n"); } /* Producer thread */ void *chef() { int cookedburgers; int mynaptime; cookedburgers = 0; while( cookedburgers < NUM_BURGERS ) { printf("Current pile has %d burgers\n", burgerpile); /* cook a burger */ cookedburgers++; printf("Chef cooked burger %d\n", cookedburgers); /* add it to the pile when space is available */ while( burgerpile >= MAX_BURGER_PILE ) ; burgerpile++; printf("Pile now has %d burgers\n", burgerpile); /* wait for a bit before next iteration */ mynaptime = random() % MAX_PRODUCER_NAP_DURATION; printf("Chef napping for %d seconds...\n", mynaptime); sleep( mynaptime ); } printf("Chef all done for the day!\n"); pthread_exit(0); } /* Consumer thread */ void *customer() { int eatenburgers; int naptime; eatenburgers = 0; while( eatenburgers < NUM_BURGERS ) { /* check the pile for a burger */ printf(" I see a pile of %d burgers\n", burgerpile); /* grab one and eat it when it is available */ while( burgerpile < 1 ) ; printf(" Now I see %d burgers. Grabbing one...\n", burgerpile); burgerpile--; eatenburgers++; printf(" Yum! I have now eaten %d burgers\n", eatenburgers); /* wait for a bit before next iteration */ naptime = random() % MAX_CONSUMER_NAP_DURATION; printf(" Napping for %d seconds...\n", naptime); sleep( naptime ); } printf(" Customer is full now! Bye!\n"); pthread_exit(0); }