Untitled
unknown
plain_text
2 years ago
2.3 kB
3
Indexable
#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() { // Get user input for the number of students printf("Enter the number of students: "); scanf("%d", &num_students); // Get user input for the number of 3D glasses printf("Enter the number of 3D glasses: "); scanf("%d", &num_glasses); // 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); }
Editor is loading...
Leave a Comment