Advanced Operating System
Advanced Operating System
Assignment 3.
Submitted to
Dr. Sajid Hussain
By
Shaneela
2023-KIU-MS5090
The Sleeping Teaching Assistant
Solution
This problem described a classic example of a synchronization
problem involving students and a teaching assistant (TA) using POSIX
threads, mutex locks, and semaphores to coordinate their activities.
Entities:
TA: The TA is a separate thread who helps students when they are
available.
Chairs: There are three chairs in the hallway outside the TA's office.
Students wait on these chairs if the TA is helping another student.
Synchronization Techniques:
Code
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#define NUM_STUDENTS 5
#define NUM_CHAIRS 3
pthread_mutex_t mutex;
int waiting_students = 0;
void *student_thread(void *id) {
while (1) {
sleep(rand() % 5);
pthread_mutex_lock(&mutex);
waiting_students++;
pthread_mutex_unlock(&mutex);
sem_wait(&student_sem); // Notify TA
} else {
pthread_mutex_unlock(&mutex);
}
}
while (1) {
pthread_mutex_lock(&mutex);
if (waiting_students > 0) {
// TA helps a student
waiting_students--;
pthread_mutex_unlock(&mutex);
} else {
pthread_mutex_unlock(&mutex);
printf("TA is napping.\n");
int main() {
pthread_t students[NUM_STUDENTS], ta;
int student_ids[NUM_STUDENTS];
pthread_mutex_init(&mutex, NULL);
sem_init(&student_sem, 0, 0);
sem_init(&ta_sem, 0, 0);
// Create TA thread
student_ids[i] = i + 1;
pthread_join(ta, NULL);
pthread_join(students[i], NULL);
pthread_mutex_destroy(&mutex);
sem_destroy(&student_sem);
sem_destroy(&ta_sem);
return 0;
Output