Advertisement
Guest User

Untitled

a guest
Nov 22nd, 2019
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.04 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <pthread.h>
  4. #include <stdlib.h>
  5. #include <unistd.h>
  6.  
  7. available_resources = 5;
  8. pthread_mutex_t mtx;
  9.  
  10. int decrease_count(int count)
  11. {
  12.     pthread_mutex_lock(&mtx);
  13.     if (available_resources < count)
  14.         {
  15.             pthread_mutex_unlock(&mtx);
  16.             return -1;
  17.         }
  18.     else
  19.         {
  20.         available_resources -= count;
  21.         printf("Got: %d , remaining: %d \n",count, available_resources);
  22.         }
  23.     pthread_mutex_unlock(&mtx);
  24.     return 1;
  25. }
  26. int increase_count(int count)
  27. {   pthread_mutex_lock(&mtx);
  28.     available_resources += count;
  29.     printf("Released: %d , remaining: %d \n",count, available_resources);
  30.     pthread_mutex_unlock(&mtx);
  31.     return 0;
  32. }
  33. void thread_init(void *arg)
  34. {  
  35.     int cnt = (int) arg;
  36.     if(decrease_count(cnt) == 1);
  37.         increase_count(cnt);
  38.     return NULL;   
  39.    
  40. }
  41. int main()
  42. {
  43.    
  44.     int count;
  45.     pthread_t thr[6];
  46.     for (int i=0; i<6; i++)
  47.     {
  48.         count = rand() % 5;
  49.         pthread_create(&thr[i], NULL, thread_init, count);
  50.     }
  51.  
  52.     for (int i=0; i <6; i++)
  53.     {
  54.         pthread_join(thr[i], NULL);
  55.     }
  56.     return 0;
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement