Advertisement
V15H4L

os_lab5

Feb 23rd, 2023 (edited)
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.57 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <pthread.h>
  4. #include <semaphore.h>
  5. #include <unistd.h>
  6.  
  7. #define N 5 // number of philosophers
  8.  
  9. sem_t forks[N]; // one semaphore for each fork
  10. sem_t sem; // counting semaphore for limiting the number of philosophers eating at the same time
  11.  
  12. void *philosopher(void *arg)
  13. {
  14.     int index = *(int*)arg;
  15.     int meals = 0;
  16.     while (meals < 10) {
  17.         // thinking
  18.         printf("Philosopher %d is thinking.\n", index);
  19.  
  20.         // get forks
  21.         sem_wait(&sem);
  22.         sem_wait(&forks[index]);
  23.         sem_wait(&forks[(index + 1) % N]);
  24.  
  25.         // eating
  26.         meals++;
  27.         printf("Philosopher %d is eating (%dth meal).\n", index, meals);
  28.         usleep(rand() % 1000000); // wait for a random amount of time
  29.  
  30.         // release forks
  31.         sem_post(&forks[index]);
  32.         sem_post(&forks[(index + 1) % N]);
  33.         sem_post(&sem);
  34.     }
  35.     return NULL;
  36. }
  37.  
  38. int main()
  39. {
  40.     // initialize semaphores
  41.     sem_init(&sem, 0, N-1);
  42.     for (int i = 0; i < N; i++) {
  43.         sem_init(&forks[i], 0, 1);
  44.     }
  45.  
  46.     // create threads for each philosopher
  47.     pthread_t threads[N];
  48.     int indices[N];
  49.     for (int i = 0; i < N; i++) {
  50.         indices[i] = i;
  51.         pthread_create(&threads[i], NULL, philosopher, &indices[i]);
  52.     }
  53.  
  54.     // wait for threads to finish
  55.     for (int i = 0; i < N; i++) {
  56.         pthread_join(threads[i], NULL);
  57.     }
  58.  
  59.     // destroy semaphores
  60.     sem_destroy(&sem);
  61.     for (int i = 0; i < N; i++) {
  62.         sem_destroy(&forks[i]);
  63.     }
  64.  
  65.     return 0;
  66. }
  67.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement