Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
2.0 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;

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_watching++;
        printf("Student %d is watching the movie.\n", student_id);
    } else {
        students_waiting++;
        printf("Student %d is waiting for 3D glasses.\n", student_id);
    }

    pthread_mutex_unlock(&mutex);

    // Simulate watching the movie
    sleep(2);

    pthread_mutex_lock(&mutex);
    if (students_watching > 0) {
        students_watching--;
        glasses_available++;
        printf("Student %d finished watching the movie.\n", student_id);
    } else {
        students_waiting--;
        printf("Student %d finished waiting but didn't watch the movie.\n", student_id);
    }

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

    pthread_mutex_unlock(&mutex);

    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 students[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 + 1;
        pthread_create(&students[i], NULL, student_thread, (void *)&student_ids[i]);
    }

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

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

    return 0;
}
Leave a Comment