/** * TI II - Fachpraktikum 2 * Copyright (C) 2006 ETH Zurich */ #include #include #include #include #include #include #include void* barber_main(void* arg); void* customer_main(void* arg); void quit(int sig); void quitsem(int sig); /***********************************************/ /* declaration */ /***********************************************/ /*given: */ static int num_barbers = 4; static int num_customers = 60; static int max_customers = 20; int i; /* number of customers in the shop */ int custom_in_shop=0; sem_t custom_in_shop_sem; /* available places on the sofa */ sem_t sofa; /* barrier hair cut */ sem_t cuthair_custom_ready; sem_t cuthair_barber_ready; /* simple barrier to ensure customer waits until barber is done */ sem_t cuthair_done; /* is cash desk free? */ sem_t cash_desk; /*barrier payment */ sem_t payment_custom_ready; sem_t payment_barber_ready; /* threads: each barber and each customer curresponds to one thread */ pthread_t* barbers; pthread_t* customers; int main(int argc, char **argv) { /****************************************************/ /* initialization */ /****************************************************/ printf("INIT: start... \n"); /* prepare threads */ barbers = malloc(num_barbers * sizeof(pthread_t)); customers = malloc(num_customers * sizeof(pthread_t)); if (barbers == NULL || customers == NULL) return -1; /* initialize semaphore */ if(sem_init(&custom_in_shop_sem, 0, 1) < 0) return -1; if(sem_init(&sofa, 0, 4) < 0) return -1; if(sem_init(&cuthair_custom_ready, 0, 0) < 0) return -1; if(sem_init(&cuthair_barber_ready, 0, 0) < 0) return -1; if(sem_init(&cuthair_done, 0, 0) < 0) return -1; if(sem_init(&cash_desk, 0, 1) < 0) return -1; if(sem_init(&payment_custom_ready, 0, 0) < 0) return -1; if(sem_init(&payment_barber_ready, 0, 0) < 0) return -1; printf("\t ... ended\n"); /**************************************************/ /* start thread */ /**************************************************/ /* create barber threads: calls barber_main() */ for (i = 0; i < num_barbers; i++) { pthread_create(&barbers[i], NULL, barber_main, (void*)i); } /* create customer threads: calls customer_main() */ for (i = 0; i < num_customers; i++) { pthread_create(&customers[i], NULL, customer_main, (void*)i); } /**************************************************/ /*let barber to their job */ /**************************************************/ /**************************************************/ /* clean up shop */ /**************************************************/ /* wait for customers to leave the shop */ for (i = 0; i < num_customers; i++) { pthread_join(customers[i], NULL); } /* no costomers -> kill the barbers */ for (i = 0; i