【发布时间】:2019-11-15 16:33:40
【问题描述】:
我正在尝试使用多线程将两个矩阵相乘。这里我在linux中使用gcc编译程序,输入线程数运行。
gcc multiThread.c -o test -lpthread
./test 4
在这里,我运行 N*N 矩阵的乘法,其中 N 从 10 到 1000,间隔为 10,并计算每次迭代的执行时间。当我运行程序时,它会出现分段错误。请帮忙。
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include<time.h>
int SIZE = 10; // Size by SIZE matrices
int num_thrd; // number of threads
int A[2000][2000], B[2000][2000], C[2000][2000];
// initialize a matrix
void init_matrix(int m[SIZE][SIZE])
{
int i, j;
for (i = 0; i < SIZE; i++)
for (j = 0; j < SIZE; j++)
m[i][j] = rand() % 100 + 1;
}
// thread function: taking "slice" as its argument
void* multiply(void* slice)
{
int s = (int)slice; // retrive the slice info
int from = (s * SIZE)/num_thrd; // note that this 'slicing' works fine
int to = ((s+1) * SIZE)/num_thrd; // even if SIZE is not divisible by num_thrd
int i,j,k;
printf("computing slice %d (from row %d to %d)\n", s, from, to-1);
for (i = from; i < to; i++)
{
for (j = 0; j < SIZE; j++)
{
C[i][j] = 0;
for ( k = 0; k < SIZE; k++)
C[i][j] += A[i][k]*B[k][j];
}
}
printf("finished slice %d\n", s);
}
int main(int argc, char* argv[])
{
FILE *outFile;
outFile = fopen("Algorithm3_Times.txt", "r");
pthread_t* thread; // pointer to a group of threads
for(int ini=0; ini<100; ini++)
{
int i;
if (argc!=2)
{
printf("Usage: %s number_of_threads\n",argv[0]);
exit(-1);
}
num_thrd = atoi(argv[1]);
init_matrix(A);
init_matrix(B);
clock_t start = clock();
thread = (pthread_t*) malloc(num_thrd*sizeof(pthread_t));
// this for loop not entered if threadd number is specified as 1
for (i = 1; i < num_thrd; i++)
{
// creates each thread working on its own slice of i
if (pthread_create (&thread[i], NULL, multiply, (void*)i) != 0 )
{
perror("Can't create thread");
free(thread);
exit(-1);
}
}
// main thread works on slice 0
// so everybody is busy
// main thread does everything if threadd number is specified as 1
multiply(0);
// main thead waiting for other thread to complete
for (i = 1; i < num_thrd; i++)
pthread_join (thread[i], NULL);
clock_t end = clock();
float time = (end - start)*1000 / CLOCKS_PER_SEC;
fprintf(outFile,"time taken for Multiplication using %d", num_thrd);
fprintf(outFile," threads = %f", time);
fprintf(outFile," milliseconds \n");
if (thread != NULL)
{
free(thread);
thread = NULL;
}
SIZE += 10;
}
printf("calculation completed.\n\n");
return 0;
}
【问题讨论】:
-
如果你想用 C 做任何远程复杂的事情,你真的需要开始使用调试器。当我终于意识到我浪费了多少生命,因为我没有尽快学习
gdb,我真的很自责。不要犯和我一样的错误!使用调试器! -
为什么要标记 C++?
-
这不是主要问题,但调用
init_matrix(A);和init_matrix(B);并未初始化您认为的数组部分。您是否收到有关不兼容指针类型的编译器警告?
标签: c linux multithreading pthreads