/* Bow / bow back Multi-threaded. Locks placed within bower struct but locking them within the bowing function. Original idea from Java Puzzlers */ #include #include // pthread_t, pthread_create #include // printf #include // sleep pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t io_mutex = PTHREAD_MUTEX_INITIALIZER; typedef struct { char name[20]; pthread_mutex_t mutex; } Friend; void initFriend(Friend* friendP, char* name) { strcpy(friendP->name, name); pthread_mutex_init(&(friendP->mutex), NULL); } void bowBack(Friend* bower, Friend* bowie); void bow(Friend* bower, Friend* bowie) { // pthread_mutex_lock(&io_mutex); printf("%s: I bow to %s.\n", bower->name, bowie->name); // pthread_mutex_unlock(&io_mutex); bowBack(bowie, bower); } void bowBack(Friend* bower, Friend* bowie) { // pthread_mutex_lock(&io_mutex); printf("%s: I bow back to %s.\n", bower->name, bowie->name); // pthread_mutex_unlock(&io_mutex); } void* bowing(void* p) { Friend** friends = (Friend**)p; // printf("In bowing\n"); //pthread_mutex_lock(&mutex); pthread_mutex_lock(&friends[0]->mutex); // pthread_yield(); sleep(1); pthread_mutex_lock(&friends[1]->mutex); // pthread_mutex_unlock(&mutex); bow(friends[0], friends[1]); pthread_mutex_unlock(&friends[0]->mutex); pthread_mutex_unlock(&friends[1]->mutex); return NULL; } int main() { Friend alphonse; initFriend(&alphonse, "Alphonse"); Friend gaston; initFriend(&gaston, "Gaston"); pthread_t tid1, tid2; Friend* ag[] = {&alphonse, &gaston}; Friend* ga[] = {&gaston, &alphonse}; pthread_create(&tid1, NULL, bowing, (void*)ag); pthread_create(&tid2, NULL, bowing, (void*)ga); // pthread_exit(0); pthread_join(tid1, NULL); pthread_join(tid2, NULL); }