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指針,並像它的結構一樣對它進行操作?

回答

1

嘗試使用a=(ThreadData*)p;

在C語言中,struct ThreadDataThreadData不同。

在這種情況下,您使用了typedef並且沒有爲該結構定義標籤,因此您不能使用struct來使用該結構。

+0

非常好,你說得對。我不習慣兩種創建結構的方式之間的差異。謝謝一堆! – Csteele5