fork download
  1. #include <stdio.h>
  2. #include <pthread.h>
  3. #include <semaphore.h>
  4.  
  5. #define MAX 100
  6.  
  7. sem_t forks[MAX];
  8. int numPhilosophers;
  9.  
  10. void* philosopher(void* arg) {
  11. int id = *(int*)arg;
  12. int left = id;
  13. int right = (id + 1) % numPhilosophers;
  14.  
  15. printf("P%d is thinking\n", id + 1);
  16.  
  17. sem_wait(&forks[left]);
  18. printf("P%d picked F%d\n", id + 1, left + 1);
  19.  
  20. sem_wait(&forks[right]);
  21. printf("P%d picked F%d\n", id + 1, right + 1);
  22.  
  23. printf("P%d is eating with F%d and F%d\n", id + 1, left + 1, right + 1);
  24.  
  25. sem_post(&forks[left]);
  26. printf("P%d released F%d\n", id + 1, left + 1);
  27.  
  28. sem_post(&forks[right]);
  29. printf("P%d released F%d\n", id + 1, right + 1);
  30.  
  31. return NULL;
  32. }
  33.  
  34. int main() {
  35. scanf("%d", &numPhilosophers);
  36. if (numPhilosophers < 2 || numPhilosophers > MAX) return 1;
  37.  
  38. pthread_t threads[MAX];
  39. int ids[MAX];
  40.  
  41. for (int i = 0; i < numPhilosophers; i++)
  42. sem_init(&forks[i], 0, 1);
  43.  
  44. for (int i = 0; i < numPhilosophers; i++) {
  45. ids[i] = i;
  46. pthread_create(&threads[i], NULL, philosopher, &ids[i]);
  47. }
  48.  
  49. for (int i = 0; i < numPhilosophers; i++)
  50. pthread_join(threads[i], NULL);
  51.  
  52. return 0;
  53. }
  54.  
Success #stdin #stdout 0s 5320KB
stdin
3
stdout
P3 is thinking
P3 picked F3
P3 picked F1
P3 is eating with F3 and F1
P3 released F3
P3 released F1
P2 is thinking
P2 picked F2
P2 picked F3
P2 is eating with F2 and F3
P2 released F2
P2 released F3
P1 is thinking
P1 picked F1
P1 picked F2
P1 is eating with F1 and F2
P1 released F1
P1 released F2