Advertisement
Guest User

Untitled

a guest
May 24th, 2017
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.15 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <math.h>
  4. #include <pthread.h>
  5.  
  6. #define Nmax 4
  7. #define Pmax 3
  8.  
  9. // Solucion:    Eliminacion de la condición de exclusion mutua.
  10. //      Eliminando los locks, no es posible que un proceso adquiera de forma exclusiva un recurso.
  11.  
  12. void *trabajo(void *tid){
  13.  
  14.     int thid, i, j, k, ya;
  15.     double x=0;
  16.     int mis_recursos[Nmax];
  17.  
  18.     thid = (int)tid;
  19.     srand(thid);
  20.     for(i=0;i<Nmax;i++){
  21.         ya=0;
  22.         while(ya==0){
  23.             j=(int) (Nmax)*(rand()/(RAND_MAX+1.0));
  24.             ya=1;
  25.             for(k=0;k<i;k++){
  26.                 if (mis_recursos[k]==j){
  27.                     ya=0;
  28.                 }
  29.             }
  30.         }
  31.         mis_recursos[i]=j;
  32.         printf("Soy %d y quiero el recurso %d\n",thid,j);
  33.         for(k=0;k<10000;k++){
  34.             x+=sqrt(sqrt(k+0.1));
  35.         }
  36.         k = (int) 2*(rand()/(RAND_MAX+1.0));
  37.         sleep(k);
  38.         printf("    Soy %d y tengo el recurso %d\n",thid,j);
  39.     }
  40.     printf("**********ACABE! Soy %d\n",thid);
  41.  
  42. }
  43.  
  44. main(){
  45.  
  46.     int i, j;
  47.     pthread_t th[Pmax];
  48.  
  49.     for(i=0;i<Pmax;i++){
  50.         j = pthread_create(&th[i],NULL,trabajo,(void *)i);
  51.         if(j){
  52.             printf("ERROR; return code from pthread_creat() is %d\n",j);
  53.             exit(-1);
  54.         }
  55.     }
  56.     for(i=0;i<Pmax;i++){
  57.         pthread_join(th[i],NULL);
  58.     }
  59.  
  60.     exit(0);
  61.  
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement