
#include <stdio.h>
#include <pthread.h>

#define MAX_NUM 50

int number = 1;
pthread_mutex_t lock;
pthread_cond_t cond;
int turn = 0; // 0, 1, 2 for three threads

void* print_numbers(void* arg) {
 int thread_id = *(int*)arg;

 while (1) {
 pthread_mutex_lock(&lock);

 while (turn != thread_id && number <= MAX_NUM) {
 pthread_cond_wait(&cond, &lock);
 }

 if (number > MAX_NUM) {
 pthread_cond_broadcast(&cond);
 pthread_mutex_unlock(&lock);
 break;
 }

 printf("Thread %d: %d\n", thread_id + 1, number);
 number++;
 turn = (turn + 1) % 3;

 pthread_cond_broadcast(&cond);
 pthread_mutex_unlock(&lock);
 }

 return NULL;
}

int main() {
 pthread_t threads[3];
 int ids[3] = {0, 1, 2};

 pthread_mutex_init(&lock, NULL);
 pthread_cond_init(&cond, NULL);

 for (int i = 0; i < 3; i++) {
 pthread_create(&threads[i], NULL, print_numbers, &ids[i]);
 }

 for (int i = 0; i < 3; i++) {
 pthread_join(threads[i], NULL);
 }

 pthread_mutex_destroy(&lock);
 pthread_cond_destroy(&cond);

 return 0;
}
