Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <semaphore.h>
- #include <pthread.h>
- #include <unistd.h>
- #include <fcntl.h>
- int **matriceA, **matriceB, **matriceC;
- int n,m,p;
- pthread_mutex_t mutex= PTHREAD_MUTEX_INITIALIZER;
- pthread_cond_t cond= PTHREAD_COND_INITIALIZER;
- int controllo=0;
- sem_t semaforo;
- void *prodotto( void* arg)
- {
- int indice;
- int i,j;
- //int appoggio[p];
- indice=*(int*)arg;
- for(i=0;i<p;i++)//scorre le colonne
- {
- for(j=0;j<n;j++)//scorre grandezza comune comune
- {
- matriceC[indice][i]+=matriceA[indice][j]*matriceB[j][i];
- }
- }
- sem_wait(&semaforo);
- controllo++;
- sem_post(&semaforo);
- pthread_mutex_lock(&mutex);
- if(controllo==m)
- pthread_cond_signal(&cond);
- pthread_mutex_unlock(&mutex);
- pthread_exit(0);
- //for(i=0;i<p;i++)
- //printf("\t%d",appoggio[i]);
- }
- void *stampa ()
- {
- int i,j;
- pthread_mutex_lock(&mutex);
- if(controllo<m)
- pthread_cond_wait(&cond,&mutex);
- pthread_mutex_unlock(&mutex);
- printf("\n\n\n\n\n Risultato:\n");
- for(i=0;i<m;i++)
- {
- for(j=0;j<p;j++)
- {
- printf("\t%d",matriceC[i][j]);
- }
- printf("\n");
- }
- pthread_exit(0);
- }
- int main(int argc, char **argv)
- {
- int i,j;
- n=atoi(argv[1]);
- m=atoi(argv[2]);
- p=atoi(argv[3]);
- matriceA= (int**)calloc(m,sizeof(int*));
- for(i=0;i<m;i++)
- matriceA[i]=(int*)calloc(n,sizeof(int));
- matriceB= (int**)calloc(n,sizeof(int*));
- for(i=0;i<n;i++)
- matriceB[i]=(int*)calloc(p,sizeof(int));
- matriceC= (int**)calloc(m,sizeof(int*));
- for(i=0;i<m;i++)
- matriceC[i]=(int*)calloc(p,sizeof(int));
- for(i=0;i<m;i++)
- {
- for(j=0;j<n;j++)
- {
- matriceA[i][j]=rand()%10;
- }
- }
- for(i=0;i<n;i++)
- {
- for(j=0;j<p;j++)
- {
- matriceB[i][j]=rand()%10;
- }
- }
- for(i=0;i<m;i++)
- {
- for(j=0;j<n;j++)
- {
- printf("\t%d",matriceA[i][j]);
- }
- printf("\n");
- }
- printf("\n\n\n");
- for(i=0;i<n;i++)
- {
- for(j=0;j<p;j++)
- {
- printf("\t%d",matriceB[i][j]);
- }
- printf("\n");
- }
- sem_init(&semaforo,0,1);
- //semaforo=sem_open("sema", O_CREAT | O_EXCL, 0777, 1);
- pthread_t id[m], controllore;
- pthread_create(&controllore, NULL, stampa, NULL);
- for(i=0;i<m; i++)
- pthread_create(&id[i], NULL, prodotto, (void*)&i);
- for(i=0;i<m;i++)
- pthread_join(id[i],NULL);
- pthread_join(controllore, NULL);
- sem_destroy(&semaforo);
- //sem_unlink("sema");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement