Advertisement
d1cor

error_contador_practica.c

Nov 1st, 2017
181
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.23 KB | None | 0 0
  1. /*******************************************
  2. * Author     : Diego Cordoba / @d1cor      *
  3. * Purpose    : juncotic.com  / um.edu.ar   *
  4. *******************************************/
  5.  
  6. /*
  7.  * Corregir este codigo para que devuelva el resutltado correcto
  8. */
  9.  
  10. #include <pthread.h>
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. #include <semaphore.h>
  14.  
  15. #define NITER 1000000
  16. #define NTHREADS 5
  17.  
  18. struct params{
  19.     int cnt;
  20. };
  21.  
  22. typedef struct params params_t;
  23.  
  24. void* Count(void*);
  25.  
  26. int main(int argc, char ** argv){
  27.     params_t p;
  28.     pthread_t tid[NTHREADS];
  29.  
  30.     int i=0;
  31.  
  32.     p.cnt = 0;
  33.  
  34.     for(i=0; i<NTHREADS; i++){
  35.         if(pthread_create((tid+i), NULL, Count, (void*)&p)){
  36.             printf("\n ERROR creating thread");
  37.             exit(1);
  38.         }
  39.     }
  40.  
  41.     for(i=0; i<NTHREADS; i++){
  42.         if(pthread_join(*(tid+i), NULL)){
  43.             printf("\n ERROR joining thread");
  44.             exit(1);
  45.         }
  46.     }
  47.  
  48.     if (p.cnt < NTHREADS * NITER)
  49.         printf("\n NOOOOOO! cnt es [%d], deberia ser %d\n", p.cnt, NTHREADS*NITER);
  50.     else
  51.         printf("\n BIEN! cnt es [%d]\n", p.cnt);
  52.  
  53.     pthread_exit(NULL);
  54. }
  55.  
  56. void* Count(void *p){
  57.     int i, tmp;
  58.     params_t *pp = (params_t*) p;
  59.    
  60.     for(i = 0; i < NITER; i++){
  61.         tmp = pp->cnt;
  62.         tmp = tmp+1;
  63.         pp->cnt = tmp;
  64.     }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement