Advertisement
Guest User

Untitled

a guest
Nov 17th, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.48 KB | None | 0 0
  1. /*Antonis Mpelantis 3583*/
  2.  
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <pthread.h>
  6. #include <semaphore.h>
  7. #include <time.h>
  8. #include <unistd.h>
  9.  
  10. pthread_mutex_t mutex0, mutex1, mutex2;
  11. pthread_t chef, cooks[3];
  12. int materials[3] = {0, 0, 0}; //materials[0] = meat, materials[1] = potatoes, materials[2] = pita
  13.  
  14. //Function used from chef to select the materials
  15. void select_materials(){
  16. int random[2];
  17. int i = (rand() % (2 - 0 + 1)) + 0, z;
  18. materials[i]++;
  19. while(1){
  20. z = (rand() % (2 - 0 + 1)) + 0;
  21. if(z != i){
  22. materials[z]++;
  23. break;
  24. }
  25. }
  26. }
  27.  
  28. void createANDconsume(){
  29. printf("Finishing and consuming the meal.\n");
  30. materials[0] == 0;
  31. materials[1] == 0;
  32. materials[2] == 0;
  33. sleep(2);
  34. }
  35.  
  36. void *cook_function(void *t){
  37. while(1){
  38. pthread_mutex_lock(&mutex1);
  39. int i;
  40. for(i = 0; i < 3; i++){
  41. printf("\n\n materiala %d: %d", i , materials[i]);
  42. }
  43.  
  44. if(materials[0] == 0){
  45. printf("Chef added potatoes and pita.\n");
  46. materials[0]++;
  47. printf("Cook 0 added meat.\n");
  48. createANDconsume();
  49. printf("The meal is over.\n\n");
  50. }
  51. else if(materials[1] == 0){
  52. printf("Chef added meat and pita.\n");
  53. materials[1]++;
  54. printf("Cook 1 added potatoes.\n");
  55. createANDconsume();
  56. printf("The meal is over.\n\n");
  57. }
  58. else if(materials[2] == 0){
  59. printf("Chef added meat and potatoes.\n");
  60. materials[2]++;
  61. printf("Cook 2 added pita.\n");
  62. createANDconsume();
  63. printf("The meal is over.\n\n");
  64. }
  65.  
  66. printf("\n\n materialb %d: %d", 0 , materials[0]);
  67. printf("\n\n materialb %d: %d", 1 , materials[1]);
  68. printf("\n\n materialb %d: %d", 2 , materials[2]);
  69. pthread_mutex_unlock(&mutex1);
  70. }
  71. }
  72.  
  73.  
  74. void *chef_function(void *t){
  75. while(1){
  76. int i;
  77. select_materials();
  78. if(materials[0] == 0){
  79. pthread_join(cooks[0], NULL);
  80. }
  81. else if(materials[1] == 0){
  82. pthread_join(cooks[1], NULL);
  83. }
  84. else if(materials[2] == 0){
  85. pthread_join(cooks[2], NULL);
  86. }
  87. }
  88. }
  89.  
  90. int main(){
  91. pthread_mutex_init(&mutex1, NULL);
  92. int i, c_thread;
  93. for(i = 0; i < 3; i++){
  94. c_thread = pthread_create(&(cooks[i]), NULL, &cook_function, NULL);
  95. }
  96. // pthread_mutex_destroy(&mutex1);
  97. c_thread = pthread_create(&chef, NULL, &chef_function, NULL);
  98. int j_thread;
  99. j_thread = pthread_join(chef, NULL);
  100. // pthread_mutex_destroy(&mutex0);
  101. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement