/* Bow / bow back Idea from Java Puzzlers */ #include // printf #include // strcpy #include // pthread_t, pthread_create struct Friend { char name[20]; }; void initFriend(struct Friend* friend, char* name) { strcpy(friend->name, name); } void bowBack(struct Friend* bowee, struct Friend* bower) { printf("%s: I bow back to %s\n", bowee->name, bower->name); } void bow(struct Friend* bower, struct Friend* bowee) { printf("%s: I bow to %s\n", bower->name, bowee->name); bowBack(bowee, bower); } int main() { struct Friend alphonse; initFriend(&alphonse, "Alphonse"); struct Friend gaston; initFriend(&gaston, "Gaston"); bow(&alphonse, &gaston); bow(&gaston, &alphonse); } void* bowing(void* p) { struct Friend** friends = (struct Friend**)p; // printf("In bowing\n"); pthread_mutex_lock(&friends[0]->mutex); pthread_mutex_lock(&friends[1]->mutex); bow(friends[0], friends[1]); pthread_mutex_unlock(&friends[0]->mutex); pthread_mutex_unlock(&friends[1]->mutex); } 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); }