#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#define NUM_BAKERS 3
#define CAKES_TO_WIN 5
pthread_mutex_t oven_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t oven_cond = PTHREAD_COND_INITIALIZER;
int oven_in_use = 0;
int winner = -1;
void* baker(void* arg) {
int id = *(int*)arg;
int cakes_baked = 0;
while (winner == -1) {
usleep(rand() % 5000 + 1000); // Random cake-making time
pthread_mutex_lock(&oven_mutex);
while (oven_in_use && winner == -1) {
printf("Baker %d is waiting for the oven...\n", id);
pthread_cond_wait(&oven_cond, &oven_mutex);
}
if (winner != -1) {
pthread_mutex_unlock(&oven_mutex);
break;
}
oven_in_use = 1;
pthread_mutex_unlock(&oven_mutex);
// Baking a cake
printf("Baker %d is baking a cake...\n", id);
usleep(rand() % 3000 + 1000); // Random baking time
pthread_mutex_lock(&oven_mutex);
oven_in_use = 0;
cakes_baked++;
printf("Baker %d finished baking! Total cakes: %d\n", id, cakes_baked);
if (cakes_baked == CAKES_TO_WIN) {
winner = id;
printf("Baker %d wins the competition!\n", id);
}
pthread_cond_signal(&oven_cond); // Signal that the oven is free
pthread_mutex_unlock(&oven_mutex);
// Small delay to allow other bakers a chance
usleep(100000); // 100ms
}
return NULL;
}
int main() {
pthread_t bakers[NUM_BAKERS];
int baker_ids[NUM_BAKERS];
srand(time(NULL));
printf("Welcome to the Pthreads Baking Competition!\n");
printf("First baker to bake %d cakes wins!\n\n", CAKES_TO_WIN);
for (int i = 0; i < NUM_BAKERS; i++) {
baker_ids[i] = i + 1;
pthread_create(&bakers[i], NULL, baker, &baker_ids[i]);
}
for (int i = 0; i < NUM_BAKERS; i++) {
pthread_join(bakers[i], NULL);
}
printf("\nCompetition ended. Baker %d is the winner!\n", winner);
return 0;
}