Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <pthread.h>
- #include <error.h>
- #include <stdio.h>
- #include <stdlib.h>
- #define N 8 // N <= 8
- typedef struct {
- int tam, row, c;
- double (*MA)[N], (*MB)[N], (*MC)[N];
- }matrix_type_t;
- typedef struct {
- int l, r;
- matrix_type_t mat;
- int result;
- } param;
- void* merge(void *w){
- param* args;
- args = (param*)w;
- int l = args->l;
- int r = args->r;
- int row = args->mat.row;
- int col = args->mat.c;
- //cout << "row = " << row << endl;
- if(l == r) {
- args->result = args->mat.MA[row][l] * args->mat.MB[l][col]; //conferir
- pthread_exit(NULL);
- }else{
- param *left, *right;
- left = (param*)malloc(sizeof(param));
- right = (param*)malloc(sizeof(param));
- // copiar dados
- int mid = (l + r)/2;
- left->l = l;
- left->r = mid;
- right->l = mid+1;
- right->r = r;
- pthread_t tleft, tright;
- pthread_create(&tleft, NULL, merge, (void*)left);
- pthread_create(&tright, NULL, merge, (void*)right);
- args->result = left->result + right->result;
- pthread_join(tleft, NULL);
- pthread_join(tright, NULL);
- free(left);
- free(right);
- }
- return NULL;
- }
- // chamar para cada linha e coluna com l=0 e r maximo
- void *mult(void *w){
- matrix_type_t *work = (matrix_type_t *) w;
- int row = work->row, c = work->c;
- work-> MC[row][c] = 0;
- for(int i=0;i<work->tam;i++){
- work->MC[row][c] += work->MA[row][i] * work->MB[i][c];
- }
- return NULL;
- }
- int main(void){
- int r, c;
- double MA[N][N], MB[N][N], MC[N][N];
- for(int i=0;i<N;i++){
- for(int j=0;j<N;j++){
- MA[i][j] = MB[i][j] = 1;
- MC[i][j] = 0;
- }
- }
- matrix_type_t *work;
- pthread_t thread[N*N];
- for(r=0;r<N;r++){
- for(c=0;c<N;c++){
- work = (matrix_type_t *) malloc(sizeof(matrix_type_t));
- work->tam = N;
- work->row = r;
- work->c = c;
- work->MA = MA;
- work->MB = MB;
- work->MC = MC;
- pthread_create (&(thread[c+r*8]), NULL, mult, (void*) work);
- }
- }
- for(int i=0;i<N*N;i++)
- pthread_join(thread[i], NULL);
- for(int i=0;i<N;i++){
- for(int j=0;j<N;j++){
- printf("%d ", MC[i][j]);
- }
- printf("\n");
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement