Advertisement
KsaneK

C - Mutex - LAB11

Jan 14th, 2018
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.59 KB | None | 0 0
  1. #include <pthread.h>
  2. #include <stdio.h>
  3. #include <unistd.h>
  4. #include <math.h>
  5. #include <stdlib.h>
  6.  
  7. pthread_mutex_t m[6];
  8. int a, b, wynik;
  9. int typ;
  10. char typy[4] = {'+', '-', '/', '*'};
  11.  
  12. void * dodawanie(void * arg)
  13. {
  14.     while(1)
  15.     {
  16.         pthread_mutex_lock(&m[2]);
  17.         typ = 0;
  18.         wynik = a + b;
  19.         pthread_mutex_unlock(&m[1]);
  20.     }
  21. }
  22.  
  23. void * odejmowanie(void * arg)
  24. {
  25.     while(1)
  26.     {
  27.         pthread_mutex_lock(&m[3]);
  28.         typ = 1;
  29.         wynik = a - b;
  30.         pthread_mutex_unlock(&m[1]);
  31.     }
  32. }
  33.  
  34. void * dzielenie(void * arg)
  35. {
  36.     while(1)
  37.     {
  38.         pthread_mutex_lock(&m[4]);
  39.         typ = 2;
  40.         wynik = a / b;
  41.         pthread_mutex_unlock(&m[1]);
  42.     }
  43. }
  44.  
  45. void * mnozenie(void * arg)
  46. {
  47.     while(1)
  48.     {
  49.         pthread_mutex_lock(&m[5]);
  50.         typ = 3;
  51.         wynik = a * b;
  52.         pthread_mutex_unlock(&m[1]);
  53.     }
  54. }
  55.  
  56. void * wyswietl(void * arg)
  57. {
  58.     while(1)
  59.     {
  60.         pthread_mutex_lock(&m[1]);
  61.         printf("%d %c %d = %d\n", a, typy[typ], b, wynik);
  62.         if(typ < 3) pthread_mutex_unlock(&m[typ+3]);
  63.         else pthread_mutex_unlock(&m[0]);
  64.     }
  65. }
  66.  
  67. int main(int argc, char ** argv)
  68. {
  69.     int i;
  70.     pthread_t threads[5];
  71.     for(int i = 1; i < 6; i++)
  72.         pthread_mutex_lock(&m[i]);
  73.     pthread_create(&(threads[0]), NULL, dodawanie, NULL);
  74.     pthread_create(&(threads[1]), NULL, odejmowanie, NULL);
  75.     pthread_create(&(threads[2]), NULL, dzielenie, NULL);
  76.     pthread_create(&(threads[3]), NULL, mnozenie, NULL);
  77.     pthread_create(&(threads[4]), NULL, wyswietl, NULL);
  78.     int n, first = 1;
  79.     while(1)
  80.     {
  81.         pthread_mutex_lock(&m[0]);
  82.         if(first){scanf("%d", &b); first = 0;}
  83.         a = b;
  84.         if((n = scanf("%d", &b)) < 1) break;
  85.         pthread_mutex_unlock(&m[2]);
  86.     }
  87.     return 0;
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement