G2A Many GEOs
SHARE
TWEET

Untitled

a guest Mar 31st, 2020 101 in 125 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <pthread.h>
  2. #include <stdio.h>
  3. #define NUM_THREADS 5
  4. #define TAM_VETOR 1000000
  5.  
  6. int elem[TAM_VETOR];
  7. int somaTotal;
  8.  
  9. pthread_mutex_t mut; //declaração do MUTEX
  10.  
  11. pthread_t threads[NUM_THREADS];
  12.  
  13.  
  14. void *SomaElementos(void *id) {
  15.   //funcão executada pelos threads
  16.   int i           = 0;
  17.   int somaParcial = 0;
  18.   for (i = id; i < TAM_VETOR; i = i + NUM_THREADS)
  19.     somaParcial = somaParcial + elem[i];
  20.   pthread_mutex_lock (&mut);
  21.     somaTotal = somaTotal + somaParcial;
  22.   pthread_mutex_unlock (&mut);
  23.   pthread_exit(NULL);
  24. }
  25.  
  26. int main (int argc, char *argv[]) {
  27.   int i, rc, t;
  28.   /* Inicializa vetor com números randômicos */
  29.   for (i = 0; i < TAM_VETOR; i++)
  30.     elem[i] = 1;
  31.  
  32.   //inicialização do mutex com atributos default
  33.   pthread_mutex_init (&mut, NULL);
  34.  
  35.   /* Cria threads para somar elementos do vetor em paralelo */
  36.   for(t = 0; t < NUM_THREADS; t++) {
  37.     rc = pthread_create(&threads[t], NULL, SomaElementos, (void *)t);
  38.   }
  39.  
  40.   /* Aguarda todos os threads terminarem a sua parte do cálculo */
  41.   for(t = 0; t < NUM_THREADS; t++) {
  42.     rc = pthread_join(threads[t], NULL);
  43.   }
  44.  
  45.   //destrói o mutex
  46.   pthread_mutex_destroy (&mut);
  47.   printf ("Resultado Final %d", somaTotal); /* Imprime resultado*/
  48. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top