fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <pthread.h>
  4. #include <semaphore.h> // Include semaphore header
  5. #include <unistd.h>
  6.  
  7. #define NUM_PHILOSOPHERS 5
  8.  
  9. sem_t forks[NUM_PHILOSOPHERS]; // Declare semaphore for forks
  10. pthread_mutex_t eatCountMutex = PTHREAD_MUTEX_INITIALIZER;
  11. int eatCount = 0;
  12.  
  13. void *philosopher(void *arg) {
  14. int id = *(int *)arg;
  15.  
  16. while (1) {
  17. printf("Philosopher %d is thinking.\n", id);
  18. sleep(rand() % 3);
  19.  
  20. printf("Philosopher %d is hungry.\n", id);
  21.  
  22. // Pick up the forks (left and right)
  23. sem_wait(&forks[id]); // Left fork
  24. sem_wait(&forks[(id + 1) % NUM_PHILOSOPHERS]); // Right fork
  25.  
  26. // Eating
  27. printf("Philosopher %d is eating.\n", id);
  28. sleep(rand() % 3);
  29.  
  30. // Put down the forks
  31. sem_post(&forks[id]); // Left fork
  32. sem_post(&forks[(id + 1) % NUM_PHILOSOPHERS]); // Right fork
  33.  
  34. // Track if each philosopher has eaten at least once
  35. pthread_mutex_lock(&eatCountMutex);
  36. eatCount++;
  37. if (eatCount >= NUM_PHILOSOPHERS) {
  38. printf("All philosophers have eaten at least once.\n");
  39. pthread_mutex_unlock(&eatCountMutex);
  40. exit(0);
  41. }
  42. pthread_mutex_unlock(&eatCountMutex);
  43. }
  44. return NULL;
  45. }
  46.  
  47. int main() {
  48. pthread_t philosophers[NUM_PHILOSOPHERS];
  49. int ids[NUM_PHILOSOPHERS];
  50.  
  51. // Initialize semaphores
  52. for (int i = 0; i < NUM_PHILOSOPHERS; i++) {
  53. ids[i] = i;
  54. sem_init(&forks[i], 0, 1); // Initialize each fork semaphore with value 1
  55. }
  56.  
  57. // Create philosopher threads
  58. for (int i = 0; i < NUM_PHILOSOPHERS; i++) {
  59. pthread_create(&philosophers[i], NULL, philosopher, (void *)&ids[i]);
  60. }
  61.  
  62. // Join philosopher threads
  63. for (int i = 0; i < NUM_PHILOSOPHERS; i++) {
  64. pthread_join(philosophers[i], NULL);
  65. }
  66.  
  67. // Destroy semaphores
  68. for (int i = 0; i < NUM_PHILOSOPHERS; i++) {
  69. sem_destroy(&forks[i]); // Clean up semaphores
  70. }
  71.  
  72. return 0;
  73. }
Success #stdin #stdout 0s 5276KB
stdin
Standard input is empty
stdout
Philosopher 4 is thinking.
Philosopher 3 is thinking.
Philosopher 2 is thinking.
Philosopher 1 is thinking.
Philosopher 0 is thinking.
Philosopher 2 is hungry.
Philosopher 2 is eating.
Philosopher 4 is hungry.
Philosopher 4 is eating.
Philosopher 3 is hungry.
Philosopher 1 is hungry.
Philosopher 2 is thinking.
Philosopher 1 is eating.
Philosopher 1 is thinking.
Philosopher 2 is hungry.
Philosopher 0 is hungry.
Philosopher 4 is thinking.
Philosopher 3 is eating.
Philosopher 0 is eating.
Philosopher 1 is hungry.
Philosopher 3 is thinking.
Philosopher 2 is eating.
Philosopher 4 is hungry.
All philosophers have eaten at least once.