Advertisement
EXTREMEXPLOIT

Philosophers Problem

Mar 21st, 2021
939
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.54 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <semaphore.h>
  3. #include <pthread.h>
  4. #include <stdlib.h>
  5. #include <unistd.h>
  6. #include <wait.h>
  7. #include <string.h>
  8. #include <stdbool.h>
  9.  
  10. #define NPHILOSOPHERS 5
  11. #define NFORKS 5
  12.  
  13. int Eating = 0;
  14. sem_t Forks[NFORKS];
  15. char* PhilosophersNames[NPHILOSOPHERS] = {"Plato", "Nietzsche", "Aristotle", "Kant", "Voltaire"};
  16.  
  17. void Think(int ID) { printf("Philosopher %s Thinking!\n", PhilosophersNames[ID]); sleep(1); }
  18. void Eat(int ID) { printf("Philosopher %s Eating!\n", PhilosophersNames[ID]); sleep(1); }
  19.  
  20. void* ThreadFunction(void* ID){
  21.     int PhilosopherID = (long) ID;
  22.     while(true){
  23.         Think(PhilosopherID);
  24.         if (PhilosopherID+1 < 5){
  25.             sem_wait(&Forks[PhilosopherID]);
  26.             sem_wait(&Forks[PhilosopherID+1]);
  27.         }
  28.         else{
  29.             sem_wait(&Forks[(PhilosopherID+1)%5]);
  30.             sem_wait(&Forks[PhilosopherID]);
  31.         }
  32.  
  33.         Eat(PhilosopherID);
  34.  
  35.         if (PhilosopherID+1 < 5){
  36.             sem_post(&Forks[PhilosopherID]);
  37.             sem_post(&Forks[PhilosopherID+1]);
  38.         }
  39.         else{
  40.             sem_post(&Forks[(PhilosopherID+1)%5]);
  41.             sem_post(&Forks[PhilosopherID]);
  42.         }
  43.     }
  44.     return NULL;
  45. }
  46.  
  47. int main() {
  48.     for (int i=0; i<NFORKS; i++) sem_init(&Forks[i], 0, 1);
  49.     pthread_t threadsID[NPHILOSOPHERS];
  50.  
  51.     for (long i=0; i<NPHILOSOPHERS; i++) pthread_create(&threadsID[i], NULL, ThreadFunction, (void*) i);
  52.     for (int i=0; i<NPHILOSOPHERS; i++) pthread_join(threadsID[i], NULL);
  53.  
  54.     return 0;
  55. }
  56.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement