嗨,我必須從文本文件中讀取數據到結構中的數組,然後啓動多個線程來計算它並最終顯示結果。現在我已經制定了文件讀取部分和線程部分以及顯示部分。數據不存儲在結構中
剩下的是神祕的BUG,當我從MyFunctions.C調用我的ReadFile函數時,它會很好地讀取文件並顯示好但是如果我在同一個文件中調用相同的函數但是從其他.c文件調用,那麼它會顯示垃圾values.I嘗試了一切,但無法跟蹤以下的BUG是我完整的程序
myheader.h
struct Matrix {
int m1[10][10];
int row;
int mult[10][10];
};
void *CalculateSquare(void *arguments);
MAIN.C
#include <stdio.h>
#include<stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include "myheader.h"
#define Row 4
#define Column 4
int main()
{
pthread_t pth[4];
struct Matrix args;
int i=0,j=0,k=0;
ReadFromFile(&args);
printf("Matrix is :\n");
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
printf("%d\t",(int)args.m1[i][j]);
}
printf("\n");
}
///////////////////////// Create New Thread and Store its Id in an array for future Use//////////////////
for(i=0;i<Row;i++)
{
args.row = i;
pthread_create(&pth[i],NULL,CalculateSquare,(void *)&args);
}
///////////////////////// Join All threads so that program waits for completion of each/////////////////
for(i=0;i<Row;i++)
{
pthread_join(pth[i],NULL);
}
printf("Waiting for Thread to Complete\n");
/////////////////////// Display the Matrix ////////////
printf("Square of the Matrix is :\n");
for(i=0;i<Row;i++)
{
for(j=0;j<Column;j++)
printf("%d\t",args.mult[i][j]);
printf("\n");
}
return 0;
}
MyFunctions.C
#include <stdio.h>
#include<stdlib.h>
#include "myheader.h"
struct Matrix ReadFromFile(struct Matrix args)
{
int col = 4, row = 4, i, j;
int temp;
FILE *fin;
fin=fopen("test.txt","r");
if (!fin)
perror("Can't open input");
//args.array = (int **)(malloc(sizeof(int**) *row));
for(i=0;i<4;i++)
{
//args.array[i] = (int **)(malloc(sizeof(int**) * col));
for(j=0;j<4;j++)
{
fscanf(fin,"%d \n",&temp);
args.m1[i][j] = (int)temp;
}
}
fclose(fin);
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
printf("%d\t",(int)args.m1[i][j]);
}
printf("\n");
}
return args;
}
/* This is our thread function.It takes the Row to Process */
void *CalculateSquare(void *arguments)
{
struct Matrix args =*((struct Matrix *) arguments);
int rowToProcess;
int j = 0;
int k = 0;
rowToProcess = (int)args.row;
printf("Thread calculating Row Number %d\n",rowToProcess);
for(j=0;j<4;j++)
{
args.mult[rowToProcess][j]=0;
for(k=0;k<4;k++)
{
//args.mult[rowToProcess][j] += (int)(args.m1[rowToProcess][k]*args.m1[k][j]);
}
}
// sleep(5);
return NULL;
}
輸出是
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Matrix is :
2 2 -1 0
0 2 1 4242343
3 -1075858606 1 0
4193048 -1075858606 4242341 0
Thread calculating Row Number 1
Thread calculating Row Number 2
Thread calculating Row Number 3
Thread calculating Row Number 3
Waiting for Thread to Complete
Square of the Matrix is :
0 909653609 0 0
0 0 0 0
0 0 0 15868726
15892704 134513372 -1217004872 15949812
這實際上是一個*參考*到矩陣結構,不是一個指針。 – 2011-04-17 21:55:08
@Chris Thompson:我以爲C不知道引用? – Chris 2011-04-17 21:56:44
這工作,但最後矩陣的平方米顯示相同的問題,所以應該改變那裏,即使它在mainfile它不起作用 – 2011-04-17 22:00:30