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.  
  35.  
  36. return 0;
  37. }
  38.  
  39. void *philosopher(void *arg) {
  40. int id = *(int *)arg;
  41. free(arg); // Free allocated memory for philosopher ID
  42.  
  43. printf("Philosopher %d is thinking\n", id);
  44. sleep(1);
  45.  
  46. printf("Philosopher %d wants to eat\n", id);
  47.  
  48. sem_wait(&chopsticks[id]); // Pick up left chopstick
  49. sem_wait(&chopsticks[(id + 1) % NUM_PHILOSOPHERS]); // Pick up right chopstick
  50.  
  51. printf("Philosopher %d is eating\n", id);
  52. sleep(2); // Simulate eating
  53.  
  54. sem_post(&chopsticks[(id + 1) % NUM_PHILOSOPHERS]); // Release right chopstick
  55. sem_post(&chopsticks[id]); // Release left chopstick
  56.  
  57. printf("Philosopher %d stops eating and came back to thinking state\n", id);
  58.  
  59. return NULL;
  60. }
  61.  
Success #stdin #stdout 0.01s 5280KB
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