22BCE1726 Baker Challenge
22BCE1726 Baker Challenge
22BCE1726 Baker Challenge
marks]
Instructions
#define NUM_STUDENTS 3
#define NUM_QUESTIONS 5
if (currentStudent == -1) {
currentStudent = id;
printf("Student %d has pressed the buzzer for Question %d.\n", id, currentQuestion + 1);
} else {
printf("Student %d has pressed the buzzer for Question %d but lost the chance to Student %d.\n", id,
currentQuestion + 1, currentStudent);
scores[id] -= 5;
}
unlock(id);
int isCorrect = (rand() % 3);
if (isCorrect) {
printf("Student %d has answered correctly and earned 10 marks for Question %d.\n", id, currentQuestion + 1);
scores[id] += 10;
} else {
printf("Student %d has answered incorrectly and lost 5 marks for Question %d.\n", id, currentQuestion + 1);
scores[id] -= 5;
int newid=-1;
do{
newid=(rand()%2);
}
while(newid==id);
printf("Question passed to Student %d.\n",newid);
int isCorrect = (rand() % 3);
if (isCorrect)
{
printf("Student %d has answered correctly and earned 5 marks for Question %d.\n", newid, currentQuestion + 1);
scores[newid] += 5;
}
else
{
printf("Student %d has answered incorrectly and lost 5 marks for Question %d.\n", newid, currentQuestion + 1);
scores[newid] -= 5;
}
}
currentQuestion++;
pthread_mutex_lock(&mutex);
currentStudent = -1;
pthread_mutex_unlock(&mutex);
usleep(1000000);
}
pthread_exit(NULL);
}
int main() {
pthread_t students[NUM_STUDENTS];
int studentIds[NUM_STUDENTS];
srand(time(NULL));
for (int i = 0; i < NUM_STUDENTS; i++) {
studentIds[i] = i;
pthread_create(&students[i], NULL, studentFunction, &studentIds[i]);
}
for (int i = 0; i < NUM_STUDENTS; i++) {
pthread_join(students[i], NULL);
}
int winningStudent = 0;
int maxScore = scores[0];
printf("Final Scores:\n");
for (int i = 0; i < NUM_STUDENTS; i++) {
printf("Student %d: %d marks\n", i, scores[i]);
}
return 0;
}
Output: