Untitled

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

// Global variables
int num_students;
int num_glasses;
int* waiting_students;
int glasses_available = 0;
pthread_mutex_t mutex;
sem_t sem_waiting_students;
sem_t sem_glasses_available;

// Function prototypes
void* student_function(void* student_id);

int main(int argc, char* argv[]) {
    // Check command line arguments
    if (argc != 3) {
        fprintf(stderr, "Usage: %s <number_of_students> <number_of_glasses>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    // Parse command line arguments
    num_students = atoi(argv[1]);
    num_glasses = atoi(argv[2]);

    // Allocate memory for arrays
    waiting_students = (int*)malloc(num_students * sizeof(int));

    // Initialize mutex and semaphores
    pthread_mutex_init(&mutex, NULL);
    sem_init(&sem_waiting_students, 0, 0);
    sem_init(&sem_glasses_available, 0, num_glasses);

    // Create student threads
    pthread_t students[num_students];
    for (int i = 0; i < num_students; ++i) {
        waiting_students[i] = i + 1;
        pthread_create(&students[i], NULL, student_function, (void*)&waiting_students[i]);
    }

    // Wait for all student threads to finish
    for (int i = 0; i < num_students; ++i) {
        pthread_join(students[i], NULL);
    }

    // Clean up resources
    free(waiting_students);
    pthread_mutex_destroy(&mutex);
    sem_destroy(&sem_waiting_students);
    sem_destroy(&sem_glasses_available);

    return 0;
}

void* student_function(void* student_id) {
    int id = *((int*)student_id);

    // Student arrives
    printf("Student %d arrives\n", id);

    // Wait for 3D glasses
    sem_wait(&sem_glasses_available);

    // Enter critical section (update shared variables)
    pthread_mutex_lock(&mutex);
    printf("Student %d gets 3D glasses\n", id);
    pthread_mutex_unlock(&mutex);

    // Simulate watching the 3D movie
    printf("Student %d watches the 3D movie\n", id);

    // Return 3D glasses
    pthread_mutex_lock(&mutex);
    printf("Student %d returns 3D glasses\n", id);
    pthread_mutex_unlock(&mutex);
    sem_post(&sem_glasses_available);

    // Exit
    printf("Student %d leaves\n", id);
    pthread_exit(NULL);
}
Leave a Comment