fork download
  1. #include <stdio.h>
  2. #include <pthread.h>
  3. #include <semaphore.h>
  4.  
  5. #define NUM_PHI 5
  6.  
  7. sem_t mutex;
  8. sem_t forks[NUM_PHI];
  9.  
  10. void* philosopher(void* num) {
  11. int id = *((int*)num);
  12.  
  13. for(int i = 0; i < 5; i++) {
  14. printf("Philosopher %d is thinking.\n", id);
  15. sem_wait(&forks[id]);
  16. sem_wait(&forks[(id + 1) % NUM_PHI]);
  17. printf("Philosopher %d is eating.\n", id);
  18. sem_post(&forks[(id + 1) % NUM_PHI]);
  19. sem_post(&forks[id]);
  20. }
  21.  
  22. return NULL;
  23. }
  24.  
  25. int main() {
  26. pthread_t threads[NUM_PHI];
  27. int ids[NUM_PHI];
  28.  
  29. sem_init(&mutex, 0, 1);
  30. for(int i = 0; i < NUM_PHI; i++) {
  31. sem_init(&forks[i], 0, 1);
  32. ids[i] = i;
  33. pthread_create(&threads[i], NULL, philosopher, &ids[i]);
  34. }
  35.  
  36. for(int i = 0; i < NUM_PHI; i++) {
  37. pthread_join(threads[i], NULL);
  38. }
  39.  
  40. sem_destroy(&mutex);
  41. for(int i = 0; i < NUM_PHI; i++) {
  42. sem_destroy(&forks[i]);
  43. }
  44.  
  45. return 0;
  46. }
  47.  
Success #stdin #stdout 0s 5284KB
stdin
Standard input is empty
stdout
Philosopher 4 is thinking.
Philosopher 4 is eating.
Philosopher 4 is thinking.
Philosopher 4 is eating.
Philosopher 4 is thinking.
Philosopher 4 is eating.
Philosopher 4 is thinking.
Philosopher 4 is eating.
Philosopher 4 is thinking.
Philosopher 4 is eating.
Philosopher 3 is thinking.
Philosopher 3 is eating.
Philosopher 3 is thinking.
Philosopher 3 is eating.
Philosopher 3 is thinking.
Philosopher 3 is eating.
Philosopher 3 is thinking.
Philosopher 3 is eating.
Philosopher 3 is thinking.
Philosopher 3 is eating.
Philosopher 2 is thinking.
Philosopher 2 is eating.
Philosopher 2 is thinking.
Philosopher 2 is eating.
Philosopher 2 is thinking.
Philosopher 2 is eating.
Philosopher 2 is thinking.
Philosopher 2 is eating.
Philosopher 2 is thinking.
Philosopher 2 is eating.
Philosopher 1 is thinking.
Philosopher 1 is eating.
Philosopher 1 is thinking.
Philosopher 1 is eating.
Philosopher 1 is thinking.
Philosopher 1 is eating.
Philosopher 1 is thinking.
Philosopher 1 is eating.
Philosopher 1 is thinking.
Philosopher 1 is eating.
Philosopher 0 is thinking.
Philosopher 0 is eating.
Philosopher 0 is thinking.
Philosopher 0 is eating.
Philosopher 0 is thinking.
Philosopher 0 is eating.
Philosopher 0 is thinking.
Philosopher 0 is eating.
Philosopher 0 is thinking.
Philosopher 0 is eating.