fork download
  1. #include<stdio.h>
  2. #include<semaphore.h>
  3. #include<pthread.h>
  4. #include<unistd.h>
  5. #include<stdlib.h>
  6. sem_t chopsticks[3];
  7. void *philosopher(void *arg);
  8. int main(){
  9. pthread_t t[3];
  10. for(int i=0;i<3;i++){
  11. sem_init(&chopsticks[i],0,1);
  12. }
  13. for(int i=0;i<3;i++){
  14. int *p=(int *)malloc(sizeof(int));
  15. *p=i;
  16. pthread_create(&t[i],NULL,philosopher,p);
  17. }
  18. for(int i=0;i<3;i++){
  19. pthread_join(t[i],NULL);
  20. }
  21. return 0;
  22. }
  23. void *philosopher(void *arg){
  24. int id=*(int *)arg;
  25. printf("Philosopher %d is thinking\n", id);
  26. sleep(1);
  27. printf("Philosopher %d wants to eat\n", id);
  28. sem_wait(&chopsticks[id]);
  29. sem_wait(&chopsticks[(id+1)%3]);
  30. printf("Philosopher %d is eating\n", id);
  31. sleep(2);
  32. printf("Philosopher %d stops eating and came back to thinking state\n", id);
  33. sem_post(&chopsticks[(id+1)%3]);
  34. sem_post(&chopsticks[id]);
  35. }
Success #stdin #stdout 0s 5304KB
stdin
Standard input is empty
stdout
Philosopher 2 is thinking
Philosopher 1 is thinking
Philosopher 0 is thinking
Philosopher 2 wants to eat
Philosopher 2 is eating
Philosopher 1 wants to eat
Philosopher 0 wants to eat
Philosopher 2 stops eating and came back to thinking state
Philosopher 1 is eating
Philosopher 1 stops eating and came back to thinking state
Philosopher 0 is eating
Philosopher 0 stops eating and came back to thinking state