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 * philosopher(void *);
  11. void eat(int);
  12. int main()
  13. {
  14. int i,a[5];
  15. pthread_t tid[5];
  16.  
  17. sem_init(&room,0,4);
  18.  
  19. for(i=0;i<5;i++){
  20. sem_init(&chopstick[i],0,1);
  21. }
  22.  
  23. for(i=0;i<5;i++){
  24. a[i]=i;
  25. pthread_create(&tid[i],NULL,philosopher,(void *)&a[i]);
  26. }
  27. for(i=0;i<5;i++){
  28. pthread_join(tid[i],NULL);
  29. }
  30. return 0;
  31. }
  32.  
  33. void * philosopher(void * num)
  34. {
  35. int phil=*(int *)num;
  36.  
  37. sem_wait(&room);
  38. printf("\nPhilosopher %d has entered room",phil);
  39. sem_wait(&chopstick[phil]);
  40. sem_wait(&chopstick[(phil+1)%5]);
  41.  
  42. eat(phil);
  43. sleep(2);
  44. printf("\nPhilosopher %d has finished eating",phil);
  45.  
  46. sem_post(&chopstick[(phil+1)%5]);
  47. sem_post(&chopstick[phil]);
  48. sem_post(&room);
  49. }
  50.  
  51. void eat(int phil)
  52. {
  53. printf("\nPhilosopher %d is eating",phil);
  54. }
Success #stdin #stdout 0s 5308KB
stdin
Standard input is empty
stdout
Philosopher 4 has entered room
Philosopher 4 is eating
Philosopher 3 has entered room
Philosopher 2 has entered room
Philosopher 1 has entered room
Philosopher 4 has finished eating
Philosopher 3 is eating
Philosopher 0 has entered room
Philosopher 3 has finished eating
Philosopher 2 is eating
Philosopher 2 has finished eating
Philosopher 1 is eating
Philosopher 1 has finished eating
Philosopher 0 is eating
Philosopher 0 has finished eating