Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <pthread.h>
- #include <semaphore.h>
- #include <unistd.h>
- #define N 5 // number of philosophers
- sem_t forks[N]; // one semaphore for each fork
- sem_t sem; // counting semaphore for limiting the number of philosophers eating at the same time
- void *philosopher(void *arg)
- {
- int index = *(int*)arg;
- int meals = 0;
- while (meals < 10) {
- // thinking
- printf("Philosopher %d is thinking.\n", index);
- // get forks
- sem_wait(&sem);
- sem_wait(&forks[index]);
- sem_wait(&forks[(index + 1) % N]);
- // eating
- meals++;
- printf("Philosopher %d is eating (%dth meal).\n", index, meals);
- usleep(rand() % 1000000); // wait for a random amount of time
- // release forks
- sem_post(&forks[index]);
- sem_post(&forks[(index + 1) % N]);
- sem_post(&sem);
- }
- return NULL;
- }
- int main()
- {
- // initialize semaphores
- sem_init(&sem, 0, N-1);
- for (int i = 0; i < N; i++) {
- sem_init(&forks[i], 0, 1);
- }
- // create threads for each philosopher
- pthread_t threads[N];
- int indices[N];
- for (int i = 0; i < N; i++) {
- indices[i] = i;
- pthread_create(&threads[i], NULL, philosopher, &indices[i]);
- }
- // wait for threads to finish
- for (int i = 0; i < N; i++) {
- pthread_join(threads[i], NULL);
- }
- // destroy semaphores
- sem_destroy(&sem);
- for (int i = 0; i < N; i++) {
- sem_destroy(&forks[i]);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement