Advertisement
Avdluna

sdasd

May 29th, 2019
544
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.65 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <pthread.h>
  4. #include <math.h>
  5. #include <unistd.h>
  6. #include <errno.h>
  7. #include <time.h>
  8.  
  9. pthread_mutex_t mutex;
  10. pthread_cond_t cond;
  11. int total = 0;
  12.  
  13. void* request(){
  14.     long int numberToSleep;
  15.  
  16.     numberToSleep = (rand() % 30) + 1;
  17.  
  18.     printf("Tempo: %ld\n", numberToSleep);
  19.  
  20.     sleep(numberToSleep);
  21.  
  22.     pthread_mutex_lock(&mutex);
  23.     total += numberToSleep;
  24.     pthread_mutex_unlock(&mutex);
  25.  
  26.     pthread_exit(NULL);
  27. }
  28.  
  29. void* timeout(){
  30.     sleep(8);
  31.     pthread_mutex_lock(&mutex);
  32.     total = -1;
  33.     pthread_cond_signal(&cond);
  34.     pthread_mutex_unlock(&mutex);
  35.  
  36.     pthread_exit(NULL);
  37. }
  38.  
  39. void* joiner(pthread_t pthreads[]){
  40.     pthread_mutex_lock(&mutex);
  41.     for (int i = 0; i < sizeof(pthreads); i++) {    
  42.         pthread_join(pthreads[i], NULL);      
  43.     }
  44.     pthread_cond_signal(&cond);
  45.     pthread_mutex_unlock(&mutex);
  46.  
  47.     pthread_exit(NULL);
  48. }
  49.  
  50. int gateway(int num_replicas) {
  51.     pthread_t pthreads[num_replicas];
  52.     pthread_t threadTimeout;
  53.     pthread_t threadJoin;
  54.  
  55.     for (int i = 0; i < num_replicas; i++) {
  56.         pthread_create(&pthreads[i], NULL, &request, NULL);
  57.     }
  58.  
  59.     pthread_create(threadTimeout, NULL, &timeout, NULL);
  60.     pthread_create(threadJoin, NULL, &joiner, pthreads);  
  61.  
  62.     pthread_mutex_lock(&mutex);
  63.     while (total == -1) {
  64.         pthread_cond_wait(&cond, &mutex);
  65.     }
  66.     pthread_mutex_unlock(&mutex);
  67.  
  68.     printf("\nTempo Total: %d\n", total);
  69.     return total;
  70. }
  71.  
  72. int main(int argc, char *argv[]){
  73.     int num_replicas;
  74.  
  75.     scanf("%d", &num_replicas);
  76.  
  77.     gateway(num_replicas);
  78.  
  79.     return 0;
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement