Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/types.h>
- #include <unistd.h>
- #include <pthread.h>
- #define NUM_OF_PHILOSOPHERS 5
- pthread_t philo[NUM_OF_PHILOSOPHERS];
- pthread_mutex_t chopstick[NUM_OF_PHILOSOPHERS];
- void *philosopher(void *m){
- unsigned int philo_n=*((unsigned int *)m); // Philosopher #
- int t;
- while(1){
- t=rand()%4+1; // Random thinking time generation
- printf("Philosopher [ %d ] THINKING (%d seconds)n",philo_n,t);
- sleep(t); // Sleep
- pthread_mutex_lock(&chopstick[philo_n]); // Lock (n)th Chopstick
- printf("Philosopher [ %d ] ----- pickup %d th chopstick (%d seconds)n",philo_n,philo_n,t);
- pthread_mutex_lock(&chopstick[(philo_n+1)%NUM_OF_PHILOSOPHERS]); // Lock (n+1)th Chopstick
- printf("Philosopher [ %d ] ----- pickup %d th chopstick (%d seconds)n",philo_n,(philo_n+1)%NUM_OF_PHILOSOPHERS,t);
- printf("Philosopher [ %d ] EATING (%d seconds)n",philo_n,t);
- t=rand()%4+1; // Random eating time generation
- sleep(t); // Sleep
- printf("Philosopher [ %d ] ----- putdown %d th chopstick (%d seconds)n",philo_n,philo_n,t);
- pthread_mutex_unlock(&chopstick[philo_n]); // Unlock (n)th Chopstick
- printf("Philosopher [ %d ] ----- putdown %d th chopstick (%d seconds)n",philo_n,(philo_n+1)%NUM_OF_PHILOSOPHERS,t);
- pthread_mutex_unlock(&chopstick[(philo_n+1)%NUM_OF_PHILOSOPHERS]); // Unlock (n)th Chopstick
- }
- }
- int main(){
- unsigned int i,j;
- for(i=0;i<NUM_OF_PHILOSOPHERS;i++)
- pthread_mutex_init(&chopstick[i],NULL); // mutex initialize
- for(j=0;j<NUM_OF_PHILOSOPHERS;j++)
- {
- pthread_create(&philo[j],NULL,&philosopher,(void *) &j); // Thread creation
- sleep(4); // MUST Sleep !!!!
- }
- pthread_join(philo[0],NULL);
- exit(0);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement