Solutions Operating Systems Exam
Solutions Operating Systems Exam
- A -> {B, C, D}
- {B, C} -> E
- {D, E} -> F
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
printf("Task A completed\n");
sem_post(&semB);
sem_post(&semC);
sem_post(&semD);
return NULL;
sem_wait(&semB);
printf("Task B completed\n");
sem_post(&semE);
return NULL;
sem_wait(&semC);
printf("Task C completed\n");
sem_post(&semE);
return NULL;
sem_wait(&semD);
printf("Task D completed\n");
sem_post(&semF);
return NULL;
sem_wait(&semE);
sem_wait(&semE);
printf("Task E completed\n");
sem_post(&semF);
return NULL;
sem_wait(&semF);
printf("Task F completed\n");
return NULL;
int main() {
pthread_t threads[6];
sem_init(&semB, 0, 0);
sem_init(&semC, 0, 0);
sem_init(&semD, 0, 0);
sem_init(&semE, 0, 0);
sem_init(&semF, 0, 0);
pthread_join(threads[i], NULL);
sem_destroy(&semB);
sem_destroy(&semC);
sem_destroy(&semD);
sem_destroy(&semE);
sem_destroy(&semF);
return 0;
}
Exercise 2: Sum and Average with Threads
Solution in C:
#include <stdio.h>
#include <pthread.h>
int array[MAX];
int n, sum = 0;
float average;
pthread_mutex_t mutex;
int local_sum = 0;
local_sum += array[i];
}
pthread_mutex_lock(&mutex);
sum += local_sum;
pthread_mutex_unlock(&mutex);
return NULL;
average = (float)sum / n;
return NULL;
pthread_t threads[3];
pthread_mutex_init(&mutex, NULL);
n = argc - 1;
pthread_join(threads[1], NULL);
pthread_join(threads[2], NULL);
pthread_mutex_destroy(&mutex);
return 0;
}
Exercise 3: Process Synchronization with Semaphores
Solutions in C:
sem_wait(&semA1);
printf("A1 executed\n");
sem_post(&semA2);
return NULL;
sem_wait(&semA2);
printf("A2 executed\n");
sem_post(&semA3);
return NULL;
sem_wait(&semA3);
printf("A3 executed\n");
sem_post(&semA1);
return NULL;
sem_init(&semA1, 0, 1);
sem_init(&semA2, 0, 0);
sem_init(&semA3, 0, 0);