PoLoMoTo

task2

Feb 21st, 2018
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. #include <sys/time.h>
  2. #include <stdio.h>
  3. #include <unistd.h>
  4. #include <pthread.h>
  5. #include <errno.h>
  6.  
  7. #define NUMP 5
  8.  
  9. pthread_mutex_t fork_mutex[NUMP];
  10. pthread_mutex_t phils_eating_lock;
  11. pthread_cond_t phils_eating_less_than_five;
  12. unsigned phils_eating;
  13.  
  14. void increment(){
  15. pthread_mutex_lock(&phils_eating_lock);
  16. while (phils_eating == 4)
  17. pthread_cond_wait(&phils_eating_less_than_five, &phils_eating_lock);
  18. phils_eating++;
  19. pthread_mutex_unlock(&phils_eating_lock);
  20. }
  21.  
  22. void decrement(){
  23. pthread_mutex_lock(&phils_eating_lock);
  24. phils_eating--;
  25. if (phils_eating < 4)
  26. pthread_cond_signal(&phils_eating_less_than_five);
  27. pthread_mutex_unlock(&phils_eating_lock);
  28. }
  29.  
  30. int main(){
  31. int i;
  32. pthread_t diner_thread[NUMP];
  33. int dn[NUMP];
  34. void *diner();
  35. for (i=0;i<NUMP;i++)
  36. pthread_mutex_init(&fork_mutex[i], NULL);
  37. pthread_cond_init(&phils_eating_less_than_five, NULL);
  38.  
  39. for (i=0;i<NUMP;i++){
  40. dn[i] = i;
  41. pthread_create(&diner_thread[i],NULL,diner,&dn[i]);
  42. }
  43. for (i=0;i<NUMP;i++)
  44. pthread_join(diner_thread[i],NULL);
  45.  
  46. for (i=0;i<NUMP;i++)
  47. pthread_mutex_destroy(&fork_mutex[i]);
  48.  
  49. pthread_exit(0);
  50.  
  51. }
  52.  
  53. void *diner(int *i){
  54. int v;
  55. int eating = 0;
  56. printf("I'm diner %d\n",*i);
  57. v = *i;
  58. while (eating < 5) {
  59. printf("%d is thinking\n", v);
  60. sleep( v/2);
  61. printf("%d is hungry\n", v);
  62. increment();
  63. pthread_mutex_lock(&fork_mutex[v]);
  64. pthread_mutex_lock(&fork_mutex[(v+1)%NUMP]);
  65. decrement();
  66. printf("%d is eating\n", v);
  67. eating++;
  68. sleep(1);
  69. printf("%d is done eating\n", v);
  70. pthread_mutex_unlock(&fork_mutex[v]);
  71. pthread_mutex_unlock(&fork_mutex[(v+1)%NUMP]);
  72.  
  73. }
  74. pthread_exit(NULL);
  75. }
Advertisement
Add Comment
Please, Sign In to add comment