二维矩阵的线程与求和

Thread and sum of bidimensional matrix

我必须计算二维矩阵中元素的总和,使用单独的线程来计算每一行的总和。然后主线程将这些总和加起来打印最终结果。 你们能看出哪里出了问题吗? (我是线程的新手)

#include <pthread.h>
#include <stdio.h>

void sumR(void* _a,int m,int n,int sum)
{
       int i;
        int (*a)[m]=_a;
        for(i=1;i<=n;i++)
                sum+=a[n][i];
}
int main()
{
        int a[20][20],sum1,sum;
        int m=3,n=3,k=3,i,j;
        for(i=1;i<=m;i++)
        {
                k=k+3;
                for(j=1;j<=n;j++)
                        a[i][j]=k;
        }
        sum1=0;
        for(i=1;i<=m;i++)
        {
                sum=0;
                pthread_t th;
                pthread_create(&th,NULL,&sumR,&a,&m,&n,&sum);
                sum1+=sum;
                pthread_join(&th,NULL);
        }
        printf("Sum of the matrix is: %d",sum1);
        return 0;
}

我看到的一个问题是您的循环基本上是这样做的:

for each row
    start thread
    add thread's sum to total
    wait for thread to exit

这是行不通的,因为您是在线程完成计算之前添加线程的总和。您需要等待线程完成:

start thread
wait for thread to exit
add thread's sum to total

但是,该模型没有利用多线程。您一次只有一个线程 运行。

您需要做的是创建所有线程并将它们存储在一个数组中。然后等待每个线程退出并将其总和添加到总数中。类似于:

for i = 0 to num_threads-1
    threads[i] = pthread_create(&threads[i], NULL, &sums[i], ...)

然后

for i = 0 to num_threads-1
    pthread_join(&threads[i], ...);
    sum += sums[i];

这样,您的所有线程都同时 运行,并且只有当线程完成时您才能收获结果。