fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <pthread.h>
  4. #include <semaphore.h>
  5. #include <unistd.h>
  6.  
  7. sem_t room;
  8. sem_t chopstick[5];
  9.  
  10. void eat(int phil);
  11.  
  12. void* philosopher(void* num) {
  13. int phil = *(int*)num;
  14.  
  15. sem_wait(&room);
  16.  
  17. printf("\nPhilosopher %d is thinking", phil);
  18. sleep(1);
  19.  
  20. sem_wait(&chopstick[phil]);
  21. sem_wait(&chopstick[(phil+1)%5]);
  22.  
  23. eat(phil);
  24.  
  25. sleep(1);
  26.  
  27. sem_post(&chopstick[phil]);
  28. sem_post(&chopstick[(phil+1)%5]);
  29.  
  30. printf("\nPhilosopher %d finished eating", phil);
  31.  
  32. sem_post(&room);
  33.  
  34. return NULL;
  35. }
  36.  
  37. void eat(int phil) {
  38. printf("\nPhilosopher %d is eating", phil);
  39. }
  40.  
  41. int main() {
  42. int i, a[5];
  43. pthread_t tid[5];
  44.  
  45. sem_init(&room, 0, 4);
  46.  
  47. for (i = 0; i < 5; i++) {
  48. sem_init(&chopstick[i], 0, 1);
  49. }
  50.  
  51. for (i = 0; i < 5; i++) {
  52. a[i] = i;
  53. pthread_create(&tid[i], NULL, philosopher, (void*) &a[i]);
  54. }
  55.  
  56. for (i = 0; i < 5; i++) {
  57. pthread_join(tid[i], NULL);
  58. }
  59.  
  60. return 0;
  61. }
  62.  
Success #stdin #stdout 0s 5284KB
stdin
Standard input is empty
stdout
Philosopher 4 is thinking
Philosopher 3 is thinking
Philosopher 2 is thinking
Philosopher 1 is thinking
Philosopher 4 is eating
Philosopher 4 finished eating
Philosopher 3 is eating
Philosopher 0 is thinking
Philosopher 3 finished eating
Philosopher 2 is eating
Philosopher 2 finished eating
Philosopher 1 is eating
Philosopher 1 finished eating
Philosopher 0 is eating
Philosopher 0 finished eating