Advertisement
Guest User

Untitled

a guest
May 4th, 2015
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <sys/types.h>
  4. #include <unistd.h>
  5. #include <pthread.h>
  6.  
  7. #define NUM_OF_PHILOSOPHERS 5
  8.  
  9. pthread_t philo[NUM_OF_PHILOSOPHERS];
  10. pthread_mutex_t chopstick[NUM_OF_PHILOSOPHERS];
  11.  
  12. void *philosopher(void *m){
  13.  
  14. unsigned int philo_n=*((unsigned int *)m); // Philosopher #
  15. int t;
  16. while(1){
  17. t=rand()%4+1; // Random thinking time generation
  18. printf("Philosopher [ %d ] THINKING (%d seconds)n",philo_n,t);
  19. sleep(t); // Sleep
  20.  
  21. pthread_mutex_lock(&chopstick[philo_n]); // Lock (n)th Chopstick
  22. printf("Philosopher [ %d ] ----- pickup %d th chopstick (%d seconds)n",philo_n,philo_n,t);
  23. pthread_mutex_lock(&chopstick[(philo_n+1)%NUM_OF_PHILOSOPHERS]); // Lock (n+1)th Chopstick
  24. printf("Philosopher [ %d ] ----- pickup %d th chopstick (%d seconds)n",philo_n,(philo_n+1)%NUM_OF_PHILOSOPHERS,t);
  25.  
  26. printf("Philosopher [ %d ] EATING (%d seconds)n",philo_n,t);
  27. t=rand()%4+1; // Random eating time generation
  28. sleep(t); // Sleep
  29.  
  30. printf("Philosopher [ %d ] ----- putdown %d th chopstick (%d seconds)n",philo_n,philo_n,t);
  31. pthread_mutex_unlock(&chopstick[philo_n]); // Unlock (n)th Chopstick
  32.  
  33. printf("Philosopher [ %d ] ----- putdown %d th chopstick (%d seconds)n",philo_n,(philo_n+1)%NUM_OF_PHILOSOPHERS,t);
  34. pthread_mutex_unlock(&chopstick[(philo_n+1)%NUM_OF_PHILOSOPHERS]); // Unlock (n)th Chopstick
  35. }
  36. }
  37.  
  38.  
  39. int main(){
  40.  
  41. unsigned int i,j;
  42.  
  43. for(i=0;i<NUM_OF_PHILOSOPHERS;i++)
  44. pthread_mutex_init(&chopstick[i],NULL); // mutex initialize
  45. for(j=0;j<NUM_OF_PHILOSOPHERS;j++)
  46. {
  47. pthread_create(&philo[j],NULL,&philosopher,(void *) &j); // Thread creation
  48. sleep(4); // MUST Sleep !!!!
  49. }
  50. pthread_join(philo[0],NULL);
  51. exit(0);
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement