我已经声明了一个结构,并试图在主程序中使用该结构的元素。我不确定这是不是正确的做法。什么是替代方法。它可以在main中声明新的矩阵和变量,然后将这些值分配给struct的值。我在结果矩阵的第一行得到全0,但第二行是正确计算的。另外,我应该动态创建线程。
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
struct v {
int i; /* row */
int j; /* column */
int M, N, K;
float** A;
float** B;
float** C;
};
void *runner(void *param); /* the thread */
int main(int argc, char *argv[]) {
int c, d, k, sum = 0;
pthread_t tid[50]; //Thread ID
int i,j, count = 0,thread_identifier,ret=5, count_dimension=0;
char ch;
struct v *data = (struct v *) malloc(sizeof(struct v));
printf("Enter the number of rows and columns of first matrix\n");
scanf("%d%d", &(data->M), &(data->K));
(data->A) = malloc((data->M)*sizeof(float*));
for ( i =0;i < data->M; i++)
(data->A[i]) =malloc((data->K)*sizeof(float));
printf("Enter the number of rows and columns of second matrix\n");
(data->B) = malloc((data->K)*sizeof(float*));
scanf("%d%d", &(data->K), &(data->N));
for( i=0;i<(data->K);i++)
(data->B[i]) = malloc((data->N)*sizeof(float));
printf("Allocate memory for result matrix \n\n");
(data->C) = malloc((data->M)*sizeof(float*));
for( i=0;i<(data->M);i++)
(data->C[i]) = malloc((data->N)*sizeof(float));
printf("Enter the elements of first matrix\n");
for( i = 0 ; i < data->M ; i++ )
for ( j = 0 ; j < data->K ; j++ )
scanf("%f", &(data->A[i][j]));
printf("Enter the elements of second matrix\n");
for( i = 0 ; i < data->K ; i++ )
for ( j = 0 ; j < data->N ; j++ )
scanf("%f", &(data->B[i][j]));
for(i = 0; i < data->M; i++)
{
j=0;
data->i = i;
data->j = j;
/* Now create the thread passing it data as a parameter */
pthread_attr_t attr; //Set of thread attributes
//Get the default attributes
pthread_attr_init(&attr);
//Create the thread
pthread_create(&tid[i],&attr,runner,data);
//printf("create worker thread %u for row %d",(unsigned int)pthread_self(),i);
printf("%lu",tid[i]);
printf("\n");
count++;
}
for(i=0;i< data->M;i++)
{
//Make sure the parent waits for all threads to complete
pthread_join(tid[i], NULL);
}
//Print out the resulting matrix
for(i = 0; i < data->M; i++) {
for(j = 0; j < data->N; j++) {
printf("%.2e ", data->C[i][j]);
}
printf("\n");
}
printf("\n");
printf("%d",count);
}
//The thread will begin control in this function
void *runner(void *param) {
struct v *data = param; // the structure that holds our data
int n,x=0, j=0; //the counter and sum
float sum = 0.00;
for(x=0;x<data->N;x++)
{
for(j=0;j<data->N;j++)
{
sum += data->A[data->i][j] * data->B[j][x];
}
data->C[data->i][x] = sum;
sum=0.00;
}
//Exit the thread
//pthread_exit(0);
}
答案 0 :(得分:1)
*(data->A) = malloc((data->M)*sizeof(float*));
应该是
data->A = malloc((data->M)*sizeof(float*));
data->A
此时尚未初始化,因此取消引用它会调用未定义的行为。此外,它是float**
,因此您希望让它指向float*
s的数组。
当然,data->B
同样适用。而且您还需要为data->C
分配内存。