Advertisement
Guest User

Untitled

a guest
Jan 27th, 2020
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.97 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <unistd.h>
  5. #include <errno.h>
  6. #include <pthread.h>
  7.  
  8. int belka = 100;
  9. int deska = 0;
  10.  
  11. int licznik=2000000;
  12. pthread_mutex_t sygnalizacja = PTHREAD_MUTEX_INITIALIZER;
  13. pthread_mutex_t mutBelka = PTHREAD_MUTEX_INITIALIZER;
  14. pthread_mutex_t mutDeska = PTHREAD_MUTEX_INITIALIZER;
  15.  
  16.  
  17. void* wykonaj1(void *a)
  18. {
  19. int i;
  20. pthread_mutex_lock(&sygnalizacja);
  21. for(i=0;i<1000000;i++)
  22. {
  23. licznik = licznik -1;
  24. }
  25. pthread_mutex_unlock(&sygnalizacja);
  26. return NULL;
  27. }
  28.  
  29. void error(char *msg)
  30. {
  31. fprintf(stderr,"%s:%s\n",msg,strerror(errno));
  32. exit(1);
  33. }
  34.  
  35. void* drwal()
  36. {
  37. while(1)
  38. {
  39. pthread_mutex_lock(&mutBelka);
  40. belka+=10;
  41. pthread_mutex_unlock(&mutBelka);
  42. //usleep(2000000);
  43. printf("Wyprodukowałem %i belek.\n", belka);
  44.  
  45.  
  46. usleep(2000000);
  47. }
  48. }
  49.  
  50. void* stolarz(int liczba)
  51. {
  52. while(1)
  53. {
  54. pthread_mutex_lock(&mutBelka);
  55. belka-=liczba;
  56. pthread_mutex_unlock(&mutBelka);
  57.  
  58. pthread_mutex_lock(&mutDeska);
  59. deska++;
  60. pthread_mutex_unlock(&mutDeska);
  61.  
  62. printf("Zrobiłem deskę z %i belek.\n", liczba);
  63. usleep(1500*1000);
  64. }
  65.  
  66.  
  67. }
  68.  
  69.  
  70.  
  71.  
  72. int main(){
  73. pthread_t t0;
  74. pthread_t t1;
  75.  
  76. pthread_t d;
  77. pthread_t s1, s2;
  78. pthread_t s3;
  79.  
  80. pthread_create(&d,NULL,drwal,NULL);
  81. //pthread_create(&s1,NULL,stolarz(4),NULL);
  82. pthread_create(&s2,NULL,stolarz(2),NULL);
  83. pthread_create(&s3,NULL,stolarz(7),NULL);
  84.  
  85. void* wynik;
  86. pthread_join(d,&wynik);
  87. //pthread_join(s1,&wynik);
  88. pthread_join(s2,&wynik);
  89. pthread_join(s3,&wynik);
  90.  
  91. if(pthread_create(&t0,NULL,wykonaj1,NULL)==-1)
  92. error("Nie mozna utworzyc watku t0");
  93. if(pthread_create(&t1,NULL,wykonaj1,NULL)==-1)
  94. error("Nie mozna utworzyc watku t1");
  95.  
  96. void* result;
  97. if(pthread_join(t0,&result)==-1)
  98. error("Blad oczekiwania na zakonczenie watku t0");
  99. if(pthread_join(t1,&result)==-1)
  100. error("Blad oczekiwania na zakonczenie watku t0");
  101.  
  102. printf("licznk na koniec ma wartosc = %i \n", licznik);
  103. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement