Advertisement
Avdluna

older sol

May 29th, 2019
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.79 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. int retcode;
  14.  
  15. void* request(){
  16.     long int numberToSleep;
  17.  
  18.     numberToSleep = (rand() % 30) + 1;
  19.  
  20.     printf("Tempo: %ld\n", numberToSleep);
  21.  
  22.     sleep(numberToSleep);
  23.  
  24.     pthread_mutex_lock(&mutex);
  25.     total += numberToSleep;
  26.     pthread_mutex_unlock(&mutex);
  27.  
  28.     pthread_exit(NULL);
  29. }
  30.  
  31. void* timeout(){
  32.     sleep(8);
  33.     pthread_mutex_lock(&mutex);
  34.     first = -1;
  35.     pthread_cond_signal(&cond);
  36. }
  37.  
  38. void* joiner(void* args){
  39.    
  40. }
  41.  
  42. int gateway(int num_replicas) {
  43.     struct timeval now;
  44.     struct timespec timeout;
  45.     pthread_t pthreads[num_replicas];
  46.     pthread_t threadTimeout;
  47.  
  48.     for (int i = 0; i < num_replicas; i++) {
  49.         pthread_create(&pthreads[i], NULL, &request, NULL);
  50.     }
  51.  
  52.    // pthread_create(threadTimeout, NULL, &timeout, NULL);  
  53.  
  54.    for (int i = 0; i < num_replicas; i++) {    
  55.             pthread_join(pthreads[i], NULL);      
  56.     }
  57.  
  58.     pthread_mutex_lock(&mutex);
  59.     gettimeofday(&now);
  60.     printf("%d seconds\n", now.tv_sec);
  61.     timeout.tv_sec = now.tv_sec + 15;
  62.     timeout.tv_nsec = now.tv_usec * 1000;
  63.     retcode = 0;
  64.     while(total > 16) {
  65.         retcode = pthread_cond_timedwait(&cond, &mutex, &timeout);
  66.         if (retcode == ETIMEDOUT) {
  67.             printf("Timeout 16s");
  68.             total =  -1;
  69.             pthread_mutex_unlock(&mutex);
  70.         }
  71.     }
  72.  
  73.     pthread_mutex_unlock(&mutex);
  74.        
  75.     printf("\nTempo Total: %d\n", total);
  76.     return total;
  77. }
  78.  
  79. int main(int argc, char *argv[]){
  80.     int num_replicas;
  81.  
  82.     scanf("%d", &num_replicas);
  83.  
  84.     gateway(num_replicas);
  85.  
  86.     return 0;
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement