views:

59

answers:

2

In this homework, two matrices should be added using a different thread for each quadrant. This is my attempt so far, it generates a seg fault that I haven't been able to identify.

#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#define N 4  //matrix dimension

int c[4][4];


int a[4][4]={1 ,3, 4, 5, 3, 4, 5, 6,7, 8, 9, 0, 2, 10, 3, 5};//test matrices

int b[4][4]={3, 4, 5, 6, 11, 7, 9, 3, 1, 1, 4, 5,1, 0, 0, 6};



void *cuadrante(void *argv[1]){

    int t,i,j,k;

    int opcion;

    opcion = atoi(argv[1]);      //meant to cast the quadrant number 


    switch (opcion){

    case 1:
        k=((N/2)-1); //A11 position 

        for (i=k;i=0;i--){          //1st quadrant
                for (j=k;j=0;j--){

                    c[i][j]=a[i][j]+b[i][j];
                }
            }
    break;

    case 2:

        k=((N/2)-1); //next to A11

        for (i=k-1;i=0;i--){            //2nd quadrant
            for (j=k;j<N;j++){

                c[i][j]=a[i][j]+b[i][j];
                }
            }

    break;

    case 3:

        t=N/2; //

        for (i=t;i<N;i++){          //3rd quadrant
                for (j=(t-1);j=0;j--){

                    c[i][j]=a[i][j]+b[i][j];
                }
        }

    break;

    case 4:

        t=N/2;      //position A22 
        for (i=t;i<N;i++){          //4th quadrant
                for (j=t;j<N;j++){

                c[i][j]=a[i][j]+b[i][j];
                 }
            }

    break;


    default: 
        printf("\n Opcion erronea. Intente de nuevo");

    }//fsw




}//end cuadrante






int main(int argc,char * argv[])
{
    int rc, t;

    pthread_t threads[4];

    for(t=0;t<4;t++){

        rc = pthread_create(&threads[t], NULL, cuadrante, (void *)argv[1]);
          if (rc){
             printf("ERROR; return code from pthread_create() is %d\n",rc);
             return -1;
          }//end if

        }//end for

   printf("Created %d threads.\n", t);
   pthread_exit(NULL);
   return 0;


}//end main
A: 

You're passing argv[1] as the parameter to all 4 threads; so won't they all end up taking the same route through the switch statement?

Also, your function declares its argument as a void **, but you're passing in a char * cast to a void *. This is bound to cause issues. You probably want this:

void *cuadrante(void *arg){

    int t,i,j,k;

    int opcion;

    opcion = atoi((char *)arg);      //meant to cast the quadrant number 

    ...
Oli Charlesworth
yeah, that isn't the issue. That's meant to test if the sum is done correctly (the matrices are fixed on the code so far, the result of each of their quadrants is known).
omgzor
@omgzor: What about my second point? About the datatypes?
Oli Charlesworth
Thanks for the edit, I missed that.
omgzor
A: 

If all else fails sprinkle the code with printf. You'll find the problem in 15 minutes.

Dialecticus