NicolaDelPrete

Sincor C

Jul 18th, 2019
117
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 <semaphore.h>
  4. #include <unistd.h>
  5. #include <pthread.h>
  6.  
  7.  
  8. int N=0;
  9. int *matrice;
  10. sem_t sem,sem2;
  11.  
  12. void *fibonacci ( void *i)
  13. {
  14.     sem_wait(&sem);
  15.     int ind,j;
  16.     ind=*(int*)i;
  17.     for(j=1;j<N;j++)
  18.     {
  19.         if(j-2<0)
  20.         {
  21.             *(matrice+ind*N+j)=*(matrice+ind*N+j-1)+*(matrice+ind*N+j-1);
  22.         }else
  23.         {
  24.             *(matrice+ind*N+j)=*(matrice+ind*N+j-1)+*(matrice+ind*N+j-2);
  25.         }
  26.     }
  27.     sem_post(&sem2);
  28.     sem_post(&sem);
  29. }
  30.  
  31. void *matrices (void*i)
  32. {
  33.     sem_wait(&sem2);   
  34.     int ind,j;
  35.     ind=*(int*)i;
  36.     for(j=0;j<N;j++)
  37.         printf("%d\t",*(matrice+ind*N+j));
  38.     printf("\n");
  39. }
  40.  
  41. int main()
  42. {
  43.     int i,sec=5000,sec2=5;
  44.     while (N>15 || N<10)
  45.     {  
  46.         printf("Inserire il valore di N:  ");
  47.         scanf("%d",&N);
  48.     }
  49.     matrice=(int*)calloc(N*N,sizeof(int));
  50.     sem_init(&sem,0,1);
  51.     sem_init(&sem2,0,0);
  52.     pthread_t riga,leggi;
  53.     for(i=0;i<N;i++)
  54.         *(matrice+i*N)=i+1;
  55.     for(i=0;i<N;i++)
  56.         {pthread_create(&riga,NULL,fibonacci,(void*)&i);usleep(sec);
  57.         pthread_create(&leggi,NULL,matrices,(void*)&i);usleep(sec);}
  58.     sleep(sec2);
  59.     pthread_join(riga,NULL);
  60.     pthread_join(leggi,NULL);
  61.     sem_destroy(&sem);
  62.     free(matrice);
  63.     return 0;
  64. }
Advertisement
Add Comment
Please, Sign In to add comment