Advertisement
Avdluna

Q4

May 28th, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.38 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.  
  7. pthread_mutex_t mutex;
  8. pthread_cond_t cond;
  9. int first = 0;
  10.  
  11. void* request(void* args){
  12.     long int numberToSleep;
  13.  
  14.     numberToSleep = (rand() % 30) + 1;
  15.  
  16.     printf("Tempo: %ld\n", numberToSleep);
  17.  
  18.     sleep(numberToSleep);
  19.  
  20.     pthread_mutex_lock(&mutex);
  21.     first = numberToSleep;
  22.     pthread_cond_signal(&cond);
  23.     printf("\nTempo do Primeiro: %ld\n", numberToSleep);
  24.     pthread_mutex_unlock(&mutex);
  25.  
  26.     pthread_exit(NULL);
  27. }
  28.  
  29. void* test(void* args){
  30.     sleep(8);
  31.     pthread_mutex_lock(&mutex);
  32.     first = -1;
  33.     pthread_cond_signal(&cond);
  34.     printf("\nTempo do Primeiro: %ld\n", numberToSleep);
  35.     pthread_mutex_unlock(&mutex);
  36.  
  37.     pthread_exit(NULL);
  38. }
  39.  
  40. int gateway(int num_replicas) {
  41.     pthread_t pthreads[num_replicas];
  42.     pthread_cond_init(&cond, NULL);
  43.     pthread_t teste;
  44.  
  45.     for (int i = 0; i < num_replicas; i++) {
  46.         pthread_create(&pthreads[i], NULL, &request, NULL);
  47.     }
  48.  
  49.     pthread_create(teste,NULL,&test,NULL);
  50.  
  51.     pthread_mutex_lock(&mutex);
  52.     while (first == 0) {
  53.         pthread_cond_wait(&cond, &mutex);
  54.     }
  55.     pthread_mutex_unlock(&mutex);
  56.  
  57.     return first;
  58. }
  59.  
  60. int main(int argc, char *argv[]){
  61.     int num_replicas;
  62.  
  63.     scanf("%d", &num_replicas);
  64.  
  65.     gateway(num_replicas);
  66.  
  67.     return 0;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement