版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_37717751/article/details/81050285
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define MAX 10000
int thread_count; // number of threads
int m; // row
int n; // column
double A[MAX][MAX]; // matrix input
double x[MAX]; // vector input
double y[MAX]; // result
void* Pth_mat_vect(void* rank);
int main(int argc, char* argv[]) {
int i, j;
// char* path;
char tmp;
FILE* fpread;
FILE* fpwrite;
long thread;
// printf("Please input the path/name of input file: ");
// gets(path);
fpread = fopen(argv[1], "r");
if(fpread == NULL) {
printf("Read error!");
return 0;
}
// fscanf(fpread, "%c", &tmp);
tmp = getc(fpread);
// if (tmp != 'm') {
// printf("Read error!");
// return 0;
// }
fscanf(fpread, "%d\n", &m);
// fscanf(fpread, "%c", &tmp);
tmp = getc(fpread);
// if (tmp != 'n') {
// printf("Read error!");
// return 0;
// }
fscanf(fpread, "%d\n", &n);
// fscanf(fpread, "%c", &tmp);
tmp = getc(fpread);
// if (tmp != 't') {
// printf("Read error!");
// return 0;
// }
fscanf(fpread, "%d\n", &thread_count);
// fscanf(fpread, "%c", &tmp);
tmp = getc(fpread);
// if (tmp != 'A') {
// printf("Read error!");
// return 0;
// }
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
if (j != n - 1)
fscanf(fpread, "%lf ", &A[i][j]);
else
fscanf(fpread, "%lf \n", &A[i][j]);
}
}
// fscanf(fpread, "%c", &tmp);
tmp = getc(fpread);
// if (tmp != 'X') {
// printf("Read error!");
// return 0;
// }
for (i = 0; i < n; i++) {
fscanf(fpread, "%lf ", &x[i]);
}
fclose(fpread);
pthread_t* thread_handles;
// thread_count = strtol(argv[1], NULL, 10);
thread_handles = malloc (thread_count*sizeof(pthread_t));
for (thread = 0; thread < thread_count; thread++) {
pthread_create(&thread_handles[thread], NULL, Pth_mat_vect, (void*) thread);
}
// printf("Hello from the main thread\n");
for (thread = 0; thread < thread_count; thread++) {
pthread_join(thread_handles[thread], NULL);
}
free(thread_handles);
fpwrite = fopen("Output.txt", "w");
if(fpwrite == NULL) {
printf("Write error!");
return 0;
}
for (i = 0; i < m; i++) {
fprintf(fpwrite, "%f ", y[i]);
}
fclose(fpwrite);
printf("%d %d %d", m, n, thread_count);
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
printf("%f ", A[i][j]);
}
}
printf("\n");
for (i = 0; i < n; i++) {
printf("%f ", x[i]);
}
return 0;
}
void* Pth_mat_vect(void* rank) {
long my_rank = (long) rank;
int i, j;
// consider that m cannnot be divided by thread_count exactly
int local_m = (m % thread_count != 0) ? ((int)(m / thread_count) + 1) : (m / thread_count);
int my_first_row = my_rank * local_m;
// the last thread
int my_last_row = ((my_rank + 1) * local_m - 1) > m - 1 ? (m - 1) : ((my_rank + 1) * local_m - 1);
for (i = my_first_row; i <= my_last_row; i++) {
y[i] = 0.0;
for (j = 0; j < n; j++) {
y[i] += A[i][j] * x[j];
}
}
return NULL;
}
在Linux环境下,使用以下命令编译生成可执行文件
gcc 文件名.c -o 文件名
测试命令如下
./文件名 sample_input.txt