基本矩阵乘法与pthreads c ++错误

时间:2014-02-11 00:57:17

标签: c++ matrix pthreads matrix-multiplication

我有一个矩阵乘法代码,我应该并行处理。我在这里有一个代码,我认为应该可以工作,但不会。它要么导致分段错误,要么给我所有的胡言乱语。任何人都可以帮忙吗?提前谢谢。

//*******************STRUCTS AND GLOBAL VARIABLES*****************************//
struct Matrix
{
       int d[SIZE][SIZE];
       };


Matrix* matrix_addr[SIZE]; // array to store the address of the matrices

int n;
int m;

pthread_mutex_t my_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t my_cond = PTHREAD_COND_INITIALIZER;

//****************************THREAD******************************************//
void* calcTerm(void* arg)
{
pthread_mutex_lock(&my_mutex);
    int sum = 0;


Matrix* m0 = (Matrix*) arg;
Matrix* m1 = (Matrix*) ((int*)arg + 1);
Matrix* m2 = (Matrix*) ((int*)arg + 2); 


cout << endl << "Print\n" << endl;
print (m0);


for (int i = 0; i < SIZE; ++i)
{
cout << "\ni = " << i << "\tn = " << m1->d[n][i] << "\tm = " << m2->d[i][m] << endl;
    sum =  sum + (m1->d[n][i] * m2->d[i][m]);
} 
cout << endl << endl << sum << endl;
m0->d[n][m] = sum;

 pthread_mutex_unlock(&my_mutex);
cout << endl << "Going out of thread\n" ;
 pthread_exit(NULL);
}

//********************************MAIN****************************************//

int main()

{
    Matrix m0, m1, m2; //Matrices are 3x3; 
                       // m0 <= m1 * m2
pthread_t id[9];   // 3x3 matrix multiplication requires 9 threads.

matrix_addr[0] = &m0;     // the pointers to the matrices are stored here.
matrix_addr[1] = &m1;
matrix_addr[2] = &m2;


    n = m = 0;       // initialize the global variable
    srand(time(NULL));  // seed rand()




for (int i = 0; i < SIZE; i++)
{
    for (int j = 0; j < SIZE; j++)
    {
        m0.d[i][j] = 0;           // m0 is being cleared for the output
        m1.d[i][j] = rand()%10;    // m1 and m2 are generated with rand()
        m2.d[i][j] = rand()%10;

    }
}
//display the input matrices
cout << "MATRIX 1:\n\n";
print (&m1);
cout << "\nMATRIX 2:\n\n";
print (&m2);
cout << "\nMATRIX 3:\n\n";
print (&m0);



for (int i = 0; i < SIZE*SIZE; i++) // run all the threads for calculating each output
{
m = i % SIZE;
n = i / SIZE;
cout << endl << "Going in to thread " << i << " with n = " << n << " and m = " << m;
    pthread_create(&id[i], NULL, calcTerm, (void*) matrix_addr);

cout << endl << "Out of thread " << i ;
//pthread_join(id[i], NULL);
    }    
//pthread_cond_wait(&my_cond, &my_mutex);
cout << endl << endl;

print_result (&m0, &m1, &m2);
return 0;



}

似乎calcTerm线程没有采用正确的指针或其他东西。它会计算乱码值,但是主结束时的最终输出打印出我开始使用的相同矩阵。

再次感谢。

0 个答案:

没有答案