![](/img/trans.png)
[英]how to create a struct and pass to a new thread via pthread_create()
[英]Pass a struct to pthread_create's startup routine
所以我有一个作业遇到麻烦。 我正在尝试使用pthreads将具有3个不同处理器的矩阵元素相加。 我有一个结构
typedef struct{
int rows;
int cols;
pid;
int localsum;
}ThreadData;
一些全局变量
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();
}
我的最终目标是通过ThreadData
结构作为参数传递我的matrixSum()
。
所以我认为我必须将matrixSum()
给出的void指针matrixSum()
转换为结构,但是这样做很麻烦。
我尝试这样做
ThreadData *a=malloc(sizeof(ThreadData));
a=(struct ThreadData*)p;
但是我得到一个warning: assignment from incompatible pointer type
错误的warning: assignment from incompatible pointer type
。 那么执行此操作的正确方法是-强制转换从参数获取的void指针,并像其本应的结构那样对其进行操作?
尝试使用a=(ThreadData*)p;
。
在C语言中, struct ThreadData
与ThreadData
不同。
在这种情况下,您使用了typedef
并且没有为该结构定义任何标签,因此您不能使用struct
来使用该结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.