fork download
  1. #include <stdio.h>
  2. #include <semaphore.h>
  3. #include <pthread.h>
  4. #include <unistd.h>
  5. #include <stdlib.h>
  6.  
  7. #define NUM_PHILOSOPHERS 3
  8.  
  9. sem_t chopsticks[NUM_PHILOSOPHERS];
  10.  
  11. void *philosopher(void *arg);
  12.  
  13. int main() {
  14. pthread_t t[NUM_PHILOSOPHERS];
  15.  
  16. // Initialize semaphores (chopsticks)
  17. for (int i = 0; i < NUM_PHILOSOPHERS; i++) {
  18. sem_init(&chopsticks[i], 0, 1); // Initialize each chopstick to 1 (unlocked)
  19. }
  20.  
  21. // Create philosopher threads
  22. for (int i = 0; i < NUM_PHILOSOPHERS; i++) {
  23. int *p = (int *)malloc(sizeof(int));
  24. *p = i;
  25. pthread_create(&t[i], NULL, philosopher, (void *)p);
  26. }
  27.  
  28. // Join philosopher threads
  29. for (int i = 0; i < NUM_PHILOSOPHERS; i++) {
  30. pthread_join(t[i], NULL);
  31. }
  32.  
  33. // Destroy semaphores
  34. for (int i = 0; i < NUM_PHILOSOPHERS; i++) {
  35. sem_destroy(&chopsticks[i]);
  36. }
  37.  
  38. return 0;
  39. }
  40.  
  41. void *philosopher(void *arg) {
  42. int id = *(int *)arg;
  43. free(arg); // Free allocated memory for philosopher ID
  44.  
  45. printf("Philosopher %d is thinking\n", id);
  46. sleep(1);
  47.  
  48. printf("Philosopher %d wants to eat\n", id);
  49.  
  50. sem_wait(&chopsticks[id]); // Pick up left chopstick
  51. sem_wait(&chopsticks[(id + 1) % NUM_PHILOSOPHERS]); // Pick up right chopstick
  52.  
  53. printf("Philosopher %d is eating\n", id);
  54. sleep(2); // Simulate eating
  55.  
  56. sem_post(&chopsticks[(id + 1) % NUM_PHILOSOPHERS]); // Release right chopstick
  57. sem_post(&chopsticks[id]); // Release left chopstick
  58.  
  59. printf("Philosopher %d stops eating and came back to thinking state\n", id);
  60.  
  61. return NULL;
  62. }
  63.  
Success #stdin #stdout 0.01s 5300KB
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