Advertisement
Diamyx

SO lab7 ex1

Nov 20th, 2019
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.42 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <sys/types.h>
  4. #include <sys/stat.h>
  5. #include <sys/mman.h>
  6. #include <errno.h>
  7. #include <unistd.h>
  8. #include <fcntl.h>
  9. #include <string.h>
  10. #include <pthread.h>
  11.  
  12. #define MAX_RESOURCES 5
  13. int available_resources = MAX_RESOURCES;
  14. pthread_mutex_t mtx;
  15.  
  16. int decrease_count(int count)
  17. {
  18.     pthread_mutex_lock(&mtx);
  19.     if(available_resources < count)
  20.     {
  21.         pthread_mutex_unlock(&mtx);
  22.         return -1;
  23.     }
  24.     else
  25.     {
  26.         available_resources -= count;
  27.         printf("Got %d resources %d remaining\n", count, available_resources);
  28.     }
  29.     pthread_mutex_unlock(&mtx);
  30.     return 0;
  31. }
  32.  
  33. int increase_count(int count)
  34. {
  35.     pthread_mutex_lock(&mtx);
  36.     available_resources += count;
  37.     printf("Released %d resources %d remaining\n", count, available_resources);
  38.     pthread_mutex_unlock(&mtx);
  39.  
  40.     return 0;
  41. }
  42.  
  43. void* solve(void *arg)
  44. {
  45.     int count = (int) arg;
  46.  
  47.     while (decrease_count(count) == -1);
  48.     increase_count(count);
  49.  
  50.     return NULL;
  51. }
  52.  
  53.  
  54. int main(int argc, char* argv[])
  55. {
  56.    
  57.     pthread_t thr[MAX_RESOURCES + 2];
  58.     printf("MAX_RESOURCES = %d\n", available_resources);
  59.     for (int i = 0; i < MAX_RESOURCES; i++)
  60.     {
  61.         int count;
  62.         count = rand() % (MAX_RESOURCES + 1);
  63.         if (pthread_create(&thr[i], NULL, solve, count))
  64.         {
  65.             perror(NULL);
  66.             return errno;
  67.         }
  68.     }
  69.  
  70.     for (int i = 0; i < MAX_RESOURCES; i++) pthread_join(thr[i], NULL);
  71.     pthread_mutex_destroy(&mtx);
  72.  
  73.     return 0;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement