操作系统实验六之多线程矩阵乘法

一、实验内容

实现多线程矩阵乘法:
操作系统实验六之多线程矩阵乘法_第1张图片

二、实验代码

#include 
#include 

#define DIMENSION 10

pthread_t hThread[DIMENSION][DIMENSION];

int J, K, M, N;
int mat1[DIMENSION][DIMENSION];
int mat2[DIMENSION][DIMENSION];
int result[DIMENSION][DIMENSION];

struct Data{
    int row;
    int col;
};

void *ThreadProc(void *data){
    struct Data *tmp = (struct Data *)data;
    int rs = 0;

    int loop;
    for(loop = 0; loop < K; loop++){
        rs += mat1[tmp->row][loop]*mat2[loop][tmp->col];
    }
    result[tmp->row][tmp->col] = rs;
}

int main(){
    int i, j;
    struct Data data[DIMENSION][DIMENSION];
    int ret;

    printf("输入矩阵行数和列数:");
    scanf("%d%d", &J, &K);  
    printf("输入矩阵:");
    for(i = 0; i < J; i++){
        for(j = 0; j < K; j++){
            scanf("%d", &mat1[i][j]);
        }
    }

    printf("输入矩阵行数和列数:");
    scanf("%d%d", &M, &N);
    printf("输入矩阵:");
    for(i = 0; i < M; i++){
        for(j = 0; j < N; j++){
            scanf("%d", &mat2[i][j]);
        }
    }
    if( K != M || J > 10 || K > 10 || M > 10 || N > 10){
        printf("Your input produrce an error\n");
        return -1;
    }

    for(i = 0; i < J; i++){
        for(j = 0; j < N; j++){
            data[i][j].row = i;
            data[i][j].col = j;

            ret = pthread_create(&hThread[i][j], NULL, ThreadProc, (void*)&data[i][j]);
            if(ret != 0){
                printf("Create thread error!\n");
                return -1;
            }
        }
    }

    for(i = 0; i < J; i++){
        for(j = 0; j < N; j++){
            pthread_join(hThread[i][j], NULL);
        }
    }

    printf("\n运算结果:\n");
    for(i = 0; i < J; i++){
        for(j = 0; j < N; j++){
            printf("%-5d ", result[i][j]);
        }
        printf("\n");
    }

    return 0;
}

三、实验结果

操作系统实验六之多线程矩阵乘法_第2张图片

你可能感兴趣的:(操作系统实验)