#include #include #include #include #include typedef enum Shape {PAPER = 2, ROCK = 1, SCISSORS = 0} Shape; char* shapeNames[] = { "scissors", "rock", "paper" }; // return 1 if shape1 beats shape2 // return 2 if shape2 beats shape1 // return 0 if shape1 and shape2 are the same shape int game(Shape shape1, Shape shape2) { int diff = shape1 - shape2; return diff < 0 ? diff + 3 : diff; } Shape playerShape[2]; int playing = 1; sem_t readyToPlay[2], readyToJudge; void* player(void* param) { int playerNo = *(int*)param; while(playing) { sem_wait(&readyToPlay[playerNo]); printf("%d\n", playerNo); playerShape[playerNo] = rand() % 3; sem_post(&readyToJudge); } } void* judge(void* param) { int points1 = 0, points2 = 0; while(points1 != 3 && points2 != 3) { sleep(1); sem_wait(&readyToJudge); sem_wait(&readyToJudge); int ret = game(playerShape[0], playerShape[1]); printf("%s vs %s\n", shapeNames[playerShape[0]], shapeNames[playerShape[1]]); if(ret == 1) { points1++; printf("Player1 wins the round - %d : %d\n", points1, points2); } if(ret == 2) { points2++; printf("Player2 wins the round - %d : %d\n", points1, points2); } if(points1 == 3 || points2 == 3) playing = 0; sem_post(&readyToPlay[0]); sem_post(&readyToPlay[1]); } } int main() { pthread_t player1, player2, moderator; int indexPlayer1 = 0, indexPlayer2 = 1; srand(time(0)); sem_init(&readyToJudge, 0, 0); sem_init(&readyToPlay[0], 0, 1); sem_init(&readyToPlay[1], 0, 1); pthread_create(&player1, 0, player, &indexPlayer1); pthread_create(&player2, 0, player, &indexPlayer2); pthread_create(&moderator, 0, judge, 0); pthread_join(player1, 0); pthread_join(player2, 0); sem_destroy(&readyToJudge); sem_destroy(&readyToPlay[0]); sem_destroy(&readyToPlay[1]); }