Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
2.3 kB
1
Indexable
Never
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <semaphore.h>

#define MAX_STUDENTS 100

int num_students;
int num_glasses;
int glasses_available;
int students_watching = 0;
int students_waiting = 0;

pthread_mutex_t mutex;
sem_t glasses_semaphore;

typedef struct {
    int id;
    int status; // 0: waiting, 1: watching
} Student;

Student students[MAX_STUDENTS];

void print_student_status() {
    printf("\n%-12s%-14s%-12s\n", "Student No", "Watching No", "Waiting No");
    for (int i = 0; i < num_students; ++i) {
        printf("%-12d%-14d%-12d\n", students[i].id, students[i].status == 1, students[i].status == 0);
    }
}

void *student_thread(void *arg) {
    int student_id = *(int *)arg;

    // Wait for available 3D glasses
    sem_wait(&glasses_semaphore);

    pthread_mutex_lock(&mutex);
    glasses_available--;

    if (students_watching < num_glasses) {
        students[student_id].status = 1; // Watching
        students_watching++;
    } else {
        students[student_id].status = 0; // Waiting
        students_waiting++;
    }

    pthread_mutex_unlock(&mutex);

    // Simulate watching the movie
    sleep(2);

    pthread_mutex_lock(&mutex);
    if (students[student_id].status == 1) {
        students_watching--;
        glasses_available++;
    } else {
        students_waiting--;
    }

    // Release 3D glasses
    sem_post(&glasses_semaphore);

    pthread_mutex_unlock(&mutex);

    print_student_status();

    pthread_exit(NULL);
}

int main() {
    printf("Enter the number of students: ");
    scanf("%d", &num_students);

    printf("Enter the number of 3D glasses: ");
    scanf("%d", &num_glasses);

    glasses_available = num_glasses;

    pthread_t student_threads[MAX_STUDENTS];
    int student_ids[MAX_STUDENTS];

    pthread_mutex_init(&mutex, NULL);
    sem_init(&glasses_semaphore, 0, num_glasses);

    for (int i = 0; i < num_students; ++i) {
        student_ids[i] = i;
        students[i].id = i;
        students[i].status = 0; // Initial status: waiting
        pthread_create(&student_threads[i], NULL, student_thread, (void *)&student_ids[i]);
    }

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

    pthread_mutex_destroy(&mutex);
    sem_destroy(&glasses_semaphore);

    return 0;
}
Leave a Comment