在C语言中使用线程求矩阵元素之和

3
问题陈述如下:计算二维矩阵中元素的总和,使用一个单独的线程计算每一行的和。主线程将这些和相加并打印出最终结果。
从目前看来,代码运行正确。唯一的问题是当我选择行数比列数要时(例如行=2,列=3),因为它仅计算前两列的总和,完全忽略第三列。
这是我用C语言写的代码,我真的很感激任何帮助理解我做错或遗漏的地方。谢谢。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

#define M 10
#define N 10

int rows, columns, a[M][N], s[M];

// compute the sum of each row

void* f(void* p) {
   int k = *((int*) p);
   int i;
   for (i = 0; i < columns; i++) {
      s[i] += a[k][i];
   }
   return NULL;
}

int main() {
    int i, j, *p, rc;
    int sum = 0;
    pthread_t th[M];

    // matrix creation
    printf("no. of rows = ");
    scanf("%d", &rows);
    printf("no. of columns = ");
    scanf("%d", &columns);

    for (i = 0; i < rows; i++) {
        for (j = 0; j < columns; j++) {
            printf("a[%d][%d] = \n", i, j);
            scanf("%d", &a[i][j]);
        }
    }

    printf("\nThe matrix is: \n");
    for(i=0; i < rows; i++) {
        for(j=0; j < columns; j++)
            printf("%d ", a[i][j]);
    printf("\n");
    }

    // thread creation
    for (i=0; i < rows; i++) {
        p = malloc(sizeof(int));
        *p = i;
        rc = pthread_create(&th[i], NULL, f, p);
        if (rc != 0) {
            printf("Thread creation failed");
            exit(-1);
        }
    }

    for (i=0; i < rows; i++) {
        pthread_join(th[i], NULL);
    }
    // compute the final sum
    for (i=0; i < rows; i++) {
        sum += s[i];
    }
    printf("The sum is = %d\n", sum);

    return 0;
    }
1个回答

0

你需要

s[k] += a[k][i];

而不是

s[i] += a[k][i];

每行的总和应该在每个row的索引处相加,因为s被声明为s[M]


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接