C 基本Pthread程序中的分段错误
我正在用C写一个程序,它将两个矩阵的对角线相乘,然后将所有值相加。我必须使用pthreads编写一个可以使用多线程的程序。 我知道我的代码目前只能运行偶数个线程,但每当我运行2个线程(或更多)时,就会出现分段错误。我不确定是什么引起的 这是我到目前为止的代码(底部的头文件):C 基本Pthread程序中的分段错误,c,multithreading,segmentation-fault,pthreads,C,Multithreading,Segmentation Fault,Pthreads,我正在用C写一个程序,它将两个矩阵的对角线相乘,然后将所有值相加。我必须使用pthreads编写一个可以使用多线程的程序。 我知道我的代码目前只能运行偶数个线程,但每当我运行2个线程(或更多)时,就会出现分段错误。我不确定是什么引起的 这是我到目前为止的代码(底部的头文件): #include "main.h" #include "parallel.h" #include <stdio.h> #include <stdlib.h>
#include "main.h"
#include "parallel.h"
#include <stdio.h>
#include <stdlib.h>
static void* thread_routine(void* rank){
long my_rank = (long)rank;
int totalthreads = num_threads;
int tasks = matrix_size;
//For when I implement a method to deal with odd numbers of threads:
int bigthreads = tasks % totalthreads;
int normthreads = totalthreads - bigthreads;
int min = tasks/totalthreads; //Number of tasks per thread
//Dividing my matrix up into equal sized chunks for each thread
for (long x = my_rank * min; x < (my_rank + 1) * min; x++)
for (long y= my_rank * min; y< (my_rank + 1) * min; y++)
sum += matrix_x[x][y] * matrix_y[y][x];
pthread_exit(NULL);
}
void parallel()
{
int totalthreads = num_threads;
pthread_t threads[totalthreads];
for (int i = 0; i < totalthreads; i++)
pthread_create(&threads[i], NULL, thread_routine, &i);
for (int i = 0; i < totalthreads; i++)
pthread_join(threads[i], NULL);
}
int main(int argc, char* argv[])
{
// Read from command line: matrix_size, num_threads
matrix_size = strtol(argv[1], NULL, 10);
num_threads = strtol(argv[2], NULL, 10);
// Generate matrices x and y randomly filled with 1s and -1s
matrix_x = (char**) malloc(matrix_size * sizeof(char*));
matrix_y = (char**) malloc(matrix_size * sizeof(char*));
for (long x=0; x<matrix_size; x++)
{
matrix_x[x] = (char*) malloc(matrix_size * sizeof(char));
matrix_y[x] = (char*) malloc(matrix_size * sizeof(char));
for (long y=0; y<matrix_size; y++)
{
matrix_x[x][y] = (rand() & 1) * 2 - 1;
matrix_y[x][y] = (rand() & 1) * 2 - 1;
}
}
// Calculate sum of diagonal of product of matrices x and y using parallel algorithm
sum = 0;
parallel();
// Output final sum, matrix size, and number of threads used
printf("%ld, %ld, %ld\n", sum, matrix_size, num_threads);
return 0;
}
#ifndef _MAIN_H
#define _MAIN_H
#include <pthread.h>
// Define global variables accessible to all threads
long matrix_size;
long num_threads;
char** matrix_x;
char** matrix_y;
pthread_mutex_t mutex;
long sum;
#endif // _MAIN_H
#ifndef _PARALLEL_H
#define _PARALLEL_H
void parallel();
#endif // _PARALLEL_H
我不知道这是唯一的问题还是导致SIGSEGV的问题,但您正在向每个线程传递相同的指针(
&I
)-fsanize=address
有助于SIGSEGV。发现另一个主要问题,这肯定是导致SIGSEGV的原因:你给long my_rank=(long)rank分配了一些超大垃圾数
记住,rank
是您传递给create
的指针。感谢您的回复,我对C和pthreads也很陌生,您有什么建议可以解决这个问题吗?当然,如果您忘记传递必要的参数,您可以很容易地得到SIGSEGV。应该有一张支票。