/* Bow / bow back Multi-threaded. Locks placed within bower struct Idea from Java Puzzlers */ #include // strcpy #include // pthread_t, pthread_create #include // printf 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(&(bower->mutex)); printf("%s: I bow to %s.\n", bower->name, bowie->name); bowBack(bowie, bower); pthread_mutex_unlock(&(bower->mutex)); } void bowBack(FRIEND* bower, FRIEND* bowie) { pthread_mutex_lock(&bower->mutex); printf("%s: I bow back to %s.\n", bower->name, bowie->name); pthread_mutex_unlock(&bower->mutex); } void* bowing(void* p) { FRIEND** friends = (FRIEND**)p; bow(friends[0], friends[1]); 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); }