c - 多线程 - C 中矩阵乘法中偶尔出现的段错误

标签 c multithreading

我正在开发一个多线程矩阵乘法的小程序。我的第一份工作是用随机整数填充矩阵的条目。在尝试将函数指针传递给 pthread_create 后,我遇到了一些段错误。我认为问题出在函数pthread_join中。

但总体来说有两个问题。

第一个是段错误并不是每次都会发生。有时代码可以工作,但大多数时候却不能。所以这真的让我很困惑。

另一个是当代码运行时,总是有几个条目尚未初始化,特别是对于matrix[0][0],它从未初始化。而且我不太知道在哪里调试那个。

这是我的代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>

#include <unistd.h>
#include <pthread.h>

#define N       5
#define MAX     10

int A[N][N];
int B[N][N];
int C[N][N];
pthread_t pid[N][N];

typedef struct {
    int row, col;
} Pos;

typedef void* (*thread_func)(void*);

void print_matrix(int M[][N]) {
    int i, j;
    for (i = 0; i < N; i++) {
        for (j = 0; j < N; j++) {
            printf("%3d", M[i][j]);
            if (j < N - 1) {
                printf(", ");
            }
        }
        printf("\n");
    }
}

void join_threads(void) {
    int i, j;
    for (i = 0; i < N; i++) {
        for (j = 0; j < N; j++) {
            pthread_join(pid[i][j], NULL);
        }
    }
}

void* fill_entry(void* arg) {
    Pos* pos = (Pos*)arg;
    A[pos->row][pos->col] = rand() % MAX;
    B[pos->row][pos->col] = rand() % MAX;
    return NULL;
}

void dispatch_jobs(thread_func job_func) {
    int i, j;
    for (i = 0; i < N; i++) {
        for (j = 0; j < N; j++) {
            Pos pos;
            pos.row = i;
            pos.col = j;
            if (pthread_create(&pid[i][j], NULL, job_func, (void*)&pos)) {
                perror("pthread_create");
                exit(-1);
            }
        }
    }
}

int main(void) {

    srand(time(NULL));

    dispatch_jobs(&fill_entry);
    join_threads();
    printf("Matrix A:\n");
    print_matrix(A);
    printf("Matrix B:\n");
    print_matrix(B);
    return 0;
}

最佳答案

Pos pos;
pos.row = i;
pos.col = j;
if (pthread_create(&pid[i][j], NULL, job_func, (void*)&pos)) {
    perror("pthread_create");
    exit(-1);
}

您正在将指向局部变量的指针传递给线程。一旦线程尝试访问数据,即取消引用指针,该变量就早已消失,被重用,并且包含垃圾数据。

关于c - 多线程 - C 中矩阵乘法中偶尔出现的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41906953/

相关文章:

c - 错误 234,有更多数据可用,有 RegQueryInfoKey 和 RegEnumValue

c - 链接中的重定位条目(C编程)

java - 将 Runnable 对象传递给扩展 Thread 类的类,然后启动它会打印意外结果

python - Windows 上线程和 PyGTK 的执行顺序

Java:从线程操作非静态变量?

c - 为什么 sscanf 需要 & %d 整数而不是 %s 字符串

c - 发送命令行参数时出现错误 : Command not found,

c - 如何在 armv7 架构中构建 mcrypt 库?

multithreading - QRunnable 试图中止任务

java - 多线程环境中 Apache HttpClient 的 Http Put 性能