So I've got an assignment that I'm having trouble with. I'm trying use pthreads to sum the elements of a matrix with 3 different processors. I have a struct
typedef struct{
int rows;
int cols;
pid;
int localsum;
}ThreadData;
some global variabls
int processors=3;
int rows=4;
int cols=4;
int matrix[10][10];
and a sum function
void *matrixSum(void *p){
//cast *a to struct ThreadData?
int sum=0;
int i=p->pid;
int size=p->rows*p->cols;
//to sequentially add a processor's 'owned' cells
int row=p-pid/p-cols;
int col=p-pid%p->cols;
int max_partition_size = ((size/processors)+1);
for(i;i<max_partition_size*processors;i+=processors){
col=i%p->cols;
row=i/p->cols;
if(i<=size-1){
sum+=matrix[row][col]+1;
}
}
p->localsum=sum;
}
so my main method looks like this:
int main(){
int totalsum=0;
ThreadData *a;
a=malloc(processors*(sizeof(ThreadData));
int i;
for(i=0;i<processors;i++){
a[i].rows=rows;
a[i].cols=cols;
a[i].pid=i;
a[i].localsum=0;
}
//just a function that iterates over the matrix to assign it some contents
fillmatrix(rows, cols);
pthread_t tid[processors];
for(i=0;i<processors;i++){
pthread_create(tid,NULL,matrixSum,(void *)&a);
totalsum+=a[i].localsum;
}
pthread_join();
}
My ultimate goal is to pass my matrixSum()
with a ThreadData
struct as the argument.
So I think I have to cast the void pointer given in matrixSum()
to a struct, but I'm having trouble doing so.
I tried doing so like this
ThreadData *a=malloc(sizeof(ThreadData));
a=(struct ThreadData*)p;
But I get a warning: assignment from incompatible pointer type
error.
So what's the proper way to do this - that is to cast the void pointer taken from the parameters, and operate on it like the struct it is meant to be?
Try using a=(ThreadData*)p;
.
In C language, struct ThreadData
is differ to ThreadData
.
In this case, you used typedef
and defined no tag to the struct, so you mustn't use struct
to use the struct.