操作系统实验——多线程计算矩阵相乘

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

没考虑过各种优化的第一个版本,仅保证计算正确.....

/**
 * @file main.cpp
 * @version 1.0.0
 * @author Victor Zhang
 * @date 2011-04-04
 */

#include 
#include 
#include 

using std::cin;
using std::cout;
using std::endl;

struct matrixArgs
{
    int *pMatrixLineA;
    int *pMatrixLineB;
    int *pResult;
    int matrixLineCount;
};

void *calculate(void *arg)
{
    matrixArgs *args = (matrixArgs*) arg;
    *(args->pResult) = 0;
    for (int i = 0; i < args->matrixLineCount; i++)
    {
        *(args->pResult) += (*(args->pMatrixLineA + i))
                            * (*(args->pMatrixLineB + i));
    }
    pthread_exit(NULL);
}

int main()
{
    cout<<"This program is designed to multiply two matrices M1(i*j) "
        <<"and M2(k*i), please enter three numbers i, j and k:";
    int i[3];
    for (int j = 0; j < 3; j++)
    {
        while (!(cin>>i[j]))
        {
            cin.clear();
            while (cin.get() != '\n') continue;
            cout<<"Please enter a number:";
        }
    }
    int matrixACount = i[1] * i[0];
    int matrixBCount = i[2] * i[0];
    int matrixResultCount = i[1] * i[2];
    int *pMatrixA, *pMatrixB, *pMatrixResult;
    matrixArgs *pMatrixArgs;
    pMatrixA = (int*) malloc(matrixACount * sizeof(int));
    pMatrixB = (int*) malloc(matrixBCount * sizeof(int));
    pMatrixResult = (int*) malloc(matrixResultCount * sizeof(int));
    pMatrixArgs = 
        (matrixArgs*) malloc(matrixResultCount * sizeof(matrixArgs));

    cout<<"Please enter "<>(*(pMatrixA + j))))
        {
            cin.clear();
            while (cin.get() != '\n') continue;
            cout<<"Please enter a number for element #"<>(*(pMatrixB + (j / i[2] + (j % i[2]) * i[0])))))
        {
            cin.clear();
            while (cin.get() != '\n') continue;
            cout<<"Please enter a number for element #"<matrixLineCount = i[0];
            pMatrixArgsCurrent->pMatrixLineA = pMatrixA + (j * i[0]);
            pMatrixArgsCurrent->pMatrixLineB = pMatrixB + (k * i[0]);
            pMatrixArgsCurrent->pResult = pMatrixResult + (j * i[2] + k);
            rc = pthread_create(pPthread + (j * i[2] + k), 
                                &attr, 
                                calculate, 
                                (void*) pMatrixArgsCurrent);

            if (rc)
            {
                cout<<"ERROR: return code from pthread_create() is "
                    <

转载于:https://my.oschina.net/wh1tew0lf/blog/15134

你可能感兴趣的:(操作系统实验——多线程计算矩阵相乘)