0
所以我有一个任务,我遇到了麻烦。我正在尝试使用pthreads将3个不同处理器的矩阵元素求和。我有一个结构将一个结构传递给pthread_create的启动例程
typedef struct{
int rows;
int cols;
pid;
int localsum;
}ThreadData;
一些全球variabls
int processors=3;
int rows=4;
int cols=4;
int matrix[10][10];
与和函数
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;
}
所以我的主要方法是这样的:
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();
}
我的最终目标是作为参数传递我的matrixSum()
与ThreadData
结构。
所以我认为我必须将matrixSum()
中给出的void指针赋给一个结构体,但我在这样做时遇到了麻烦。
我试着这样做这样
ThreadData *a=malloc(sizeof(ThreadData));
a=(struct ThreadData*)p;
但我得到一个warning: assignment from incompatible pointer type
错误。 那么有什么正确的方法来做到这一点 - 那就是从参数中获取void指针,并像它的结构一样对它进行操作?
非常好,你说得对。我不习惯两种创建结构的方式之间的差异。谢谢一堆! – Csteele5