PoLoMoTo

task1

Feb 21st, 2018
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 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 is_trying_to_eating;
  11.  
  12. int main(){
  13. int i;
  14. pthread_t diner_thread[NUMP];
  15. int dn[NUMP];
  16. void *diner();
  17. for (i=0;i<NUMP;i++)
  18. pthread_mutex_init(&fork_mutex[i], NULL);
  19.  
  20. for (i=0;i<NUMP;i++){
  21. dn[i] = i;
  22. pthread_create(&diner_thread[i],NULL,diner,&dn[i]);
  23. }
  24. for (i=0;i<NUMP;i++)
  25. pthread_join(diner_thread[i],NULL);
  26.  
  27. for (i=0;i<NUMP;i++)
  28. pthread_mutex_destroy(&fork_mutex[i]);
  29.  
  30. pthread_exit(0);
  31.  
  32. }
  33.  
  34. void *diner(int *i){
  35. int v;
  36. int eating = 0;
  37. printf("I'm diner %d\n",*i);
  38. v = *i;
  39. while (eating < 5) {
  40. printf("%d is thinking\n", v);
  41. sleep( v/2);
  42. printf("%d is hungry\n", v);
  43. pthread_mutex_lock(&is_trying_to_eating);
  44. pthread_mutex_lock(&fork_mutex[v]);
  45. pthread_mutex_lock(&fork_mutex[(v+1)%NUMP]);
  46. pthread_mutex_unlock(&is_trying_to_eating);
  47. printf("%d is eating\n", v);
  48. eating++;
  49. sleep(1);
  50. printf("%d is done eating\n", v);
  51. pthread_mutex_unlock(&fork_mutex[v]);
  52. pthread_mutex_unlock(&fork_mutex[(v+1)%NUMP]);
  53. }
  54. pthread_exit(NULL);
  55. }
Advertisement
Add Comment
Please, Sign In to add comment