首页 > 解决方案 > 使用 pthread 的矩阵乘法问题

问题描述

我正在用 C 编写一个程序,该程序仅将 2 个矩阵的对角线相乘,然后将所有值相加。我必须编写一个可以使用 pthreads 使用多个线程的程序。

我通过给它矩阵的大小和线程数来执行代码。

./program_name matrix_size num_threads

但是,它并没有给我正确的总和,并且使用相同的矩阵大小/线程数多次运行代码会产生不同的结果,即使伪随机矩阵对于任何一种大小都是相同的(例如:所有矩阵大小 100 相同,等等)

到目前为止,这是我的代码(底部的头文件):

#include "main.h"
#include "parallel.h"

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

static void* thread_routine(void* rank){
    long my_rank = (int)(intptr_t)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, (void*)(intptr_t)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;
}

这些是头文件:

主.h:

#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

并行.h:

#ifndef _PARALLEL_H
#define _PARALLEL_H

void parallel();

#endif // _PARALLEL_H

标签: cmatrixpthreads

解决方案


推荐阅读