Advertisement
Guest User

Untitled

a guest
Jan 28th, 2020
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.76 KB | None | 0 0
  1. #include <pthread.h>
  2. #include <sys/types.h>
  3. #include <unistd.h>
  4. #include <stdlib.h>
  5. #include <stdio.h>
  6.  
  7. unsigned int truskawkaNaKrzaczku = 0;
  8. unsigned int zebrana = 0;
  9. unsigned int truskawkaWKoszyczku = 0;
  10.  
  11. pthread_mutex_t mutex;
  12.  
  13.  
  14. void lock(void){
  15. pthread_mutex_lock(&mutex);
  16. }
  17.  
  18. void unlock(void){
  19. pthread_mutex_unlock(&mutex);
  20. }
  21.  
  22. void* zbieracz(void* arg){
  23. while (1)
  24. {
  25. lock();
  26. truskawkaNaKrzaczku = rand() % 10;
  27. zebrana = 1;
  28. unlock();
  29. printf("Zbieracz\n");
  30. usleep(800*1000);
  31. }
  32. }
  33.  
  34. void* maciek(void* arg){
  35. while(1)
  36. {
  37. unsigned int zjadlem = 0;
  38. lock();
  39. if(truskawkaWKoszyczku >= 5){
  40. truskawkaWKoszyczku -= 5;
  41. zjadlem = 1;
  42. }
  43. unlock();
  44. printf("Maciek, zjadlem? %d\n", zjadlem);
  45. usleep(1500*1000);
  46. }
  47. }
  48.  
  49. void* inspektor(void* arg){
  50. while(1)
  51. {
  52. unsigned int fajnaTruskawka = 0;
  53. lock();
  54. if(truskawkaNaKrzaczku > 6 && zebrana == 1){
  55. ++truskawkaWKoszyczku;
  56. fajnaTruskawka = 1;
  57. }
  58. zebrana = 0;
  59. unlock();
  60. printf("Inspektor, truskawka byla fajna? %d\n", fajnaTruskawka);
  61. usleep(300*1000);
  62. }
  63. }
  64.  
  65.  
  66. int main(void){
  67. pthread_t threadMaciek;
  68. pthread_t threadZbieracz;
  69. pthread_t threadInspektor;
  70. pthread_create(&threadMaciek, NULL, maciek, NULL);
  71. pthread_create(&threadZbieracz, NULL, zbieracz, NULL);
  72. pthread_create(&threadInspektor, NULL, inspektor, NULL);
  73. pthread_join(threadMaciek, NULL);
  74. pthread_join(threadZbieracz, NULL);
  75. pthread_join(threadInspektor, NULL);
  76. // maciek(&mutex);
  77. // zbieracz(&mutex);
  78. // inspektor(&mutex);
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement