c - 使用c中的线程对矩阵中的元素求和

标签 c multithreading unix matrix

问题陈述是这样的:计算二维矩阵中元素的总和,使用单独的线程计算每一行的总和/强>。主线程将这些总和加起来打印最终结果。

据我目前所见,代码运行正确。唯一的问题是当我选择的行数小于列数时(例如行 = 2,列 = 3),因为它只计算前 2 列的总和,完全忽略第三个。

这是我用 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;
    }

最佳答案

你需要

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

代替

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

s 被声明为 s[M] 时,每行的总和应添加到每个 row 的每个索引中。

关于c - 使用c中的线程对矩阵中的元素求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30141229/

相关文章:

c# - 我如何在 Semaphore 和 SemaphoreSlim 之间进行选择?

shell - 从unix中的内部列中删除csv文件中的新行字符

unix - curl | tar - gzip : stdin: not in gzip format

c - 首先使用 malloc 设置堆?

multithreading - Vibe.D 是多线程来处理并发请求的吗?

Java线程和HTTP请求死锁

windows - 让PHP命令行逐页显示phpinfo?

c - 需要 __alignof__ 的调试符号

c - 使用 C 中的链表和结构实现队列

c - "bytes numbered from 0 (LSB) to 3 (MSB)"是什么意思?