Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <pthread.h>
- #include <time.h>
- #include <stdlib.h>
- #include <stdio.h>
- #define N 5
- #define LEFT ((i+N-1)%N)
- #define RIGHT ((i+1)%N)
- #define THINKING 0
- #define HUNGRY 1
- #define EATING 2
- int state[N];
- int phil[N] = {0,1,2,3,4};
- pthread_mutex_t the_mutex;
- pthread_mutex_t s[N];
- void eat(int i)
- {
- if ( state[i] == EATING )
- printf("Philosopher %d is eating with fork %d and %d\n", i, LEFT, RIGHT);
- //usleep(100000);
- }
- void think(int i)
- {
- if ( state[i] == THINKING )
- printf("Philosopher %d is thinking\n", i);
- //usleep(10000);
- }
- void hungry(int i)
- {
- if ( state[i] == HUNGRY )
- printf("Philosopher %d is hungry\n", i);
- }
- void test(int i)
- {
- if (state[i] == HUNGRY && state[LEFT] != EATING
- && state[RIGHT] != EATING)
- {
- state[i] = EATING;
- eat(i);
- pthread_mutex_unlock(&s[i]);
- }
- }
- void takefork(int i)
- {
- pthread_mutex_lock(&the_mutex);
- state[i] = HUNGRY;
- hungry(i);
- test(i);
- pthread_mutex_unlock(&the_mutex);
- pthread_mutex_lock(&s[i]);
- }
- void putfork(int i)
- {
- pthread_mutex_lock(&the_mutex);
- state[i] = THINKING;
- test(LEFT);
- test(RIGHT);
- pthread_mutex_unlock(&the_mutex);
- }
- void *philosopher(void * num)
- {
- int i = (int)num;
- while (1)
- {
- think(i);
- takefork(i); //critical region start
- eat(i);
- putfork(i); //critical region end
- }
- }
- int main()
- {
- int i;
- pthread_t phil_id[N];
- pthread_mutex_init(&the_mutex, 0);
- for (i= 0; i < N; i++)
- {
- pthread_mutex_init(&s[i], 0);
- }
- for (i= 0; i < N; i++)
- {
- pthread_create(&phil_id[i], 0, philosopher, (void*)phil[i]);
- }
- for (i = 0; i > -1; i--)
- {
- pthread_join(phil[i], NULL);
- }
- pthread_mutex_destroy(&the_mutex);
- for (i = 0; i < N; i++)
- {
- pthread_mutex_destroy(&s[i]);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement