【发布时间】:2014-04-23 14:23:24
【问题描述】:
我的问题是我想用两个矩阵相乘来更新一个矩阵,使用线程。以下是我的代码
#include <iostream>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <iostream>
#include <ctime>
#include <cmath>
#include <vector>
using namespace std;
int thread_count; // For Command Line Argument
int l;
int m;
int n;
int start_Task;
int stop_Task;
void *Hello(void* rank); // Prototype of a thread function
int main(int argc,char* argv[])
{
int thread_id;
thread_count = atoi(argv[1]);
int l = atoi(argv[2]);
int m = atoi(argv[3]);
int n = atoi(argv[4]);
int A[l][m]; //creates A l*m matrix or a 2d array.
for(int i=0; i<l; i++) //This loops on the rows.
{
for(int j=0; j<m; j++) //This loops on the columns
{
A[i][j] = i+j; // Allocating values to A matrix
}
}
int B[m][n]; //creates B m*n matrix or a 2d array.
for(int i=0; i<m; i++) //This loops on the rows.
{
for(int j=0; j<n; j++) //This loops on the columns
{
B[i][j] = i+j+1; // Allocating values to B matrix
}
}
int C[l][n]; //creates C m*n matrix or a 2d array.
int remainder = l % thread_count;
int allocatedProcess = l/thread_count;
start_Task =0;
//cout<<remainder<<" "<<allocatedProcess<<endl;
pthread_t myThreads[thread_count];
//creates a certain number of threads
for(thread_id = 0; thread_id < thread_count; thread_id++)
{
stop_Task = start_Task + allocatedProcess;
pthread_create(&myThreads[thread_id], NULL,Hello, (void*)thread_id);
start_Task = stop_Task;
}
cout<<"Hello from the main thread \n"<<endl;
for(int i=0; i<l; i++) //This loops on the rows.
{
for(int j=0; j<n; j++) //This loops on the columns
{
cout<<"Values in Final Matrix is"<<C[i][j]<<endl;
}
}
//wait until all threads finish
for(thread_id = 0; thread_id<thread_count; thread_id++)
pthread_join(myThreads[thread_id],NULL);
return 0;
}//main
void *Hello(void* rank)
{
for(int i=start_Task; i<stop_Task; i++) //This loops on the rows.
{
for(int j=0; j<n; j++) //This loops on the columns
{
int sum = 0;
for(int k=0; k<m; k++) //This loops on the columns
{
sum += A[i][k] * B[k][j]; // Allocating values to C matrix
//product[row][col] += aMatrix[row][inner] * bMatrix[inner][col];
}
C[i][j] = sum;
cout << C[i][j] << " ";
}
cout << "\n";
}
int my_rank = (long)rank;
cout<<"Thread_"<<my_rank<<" of "<<thread_count<<endl;
return NULL;
}
我面临的问题是我无法让我的矩阵全局初始化,因为维度本身就是全局的。请更新我正确的方法来实现它。
【问题讨论】:
-
如果有任何解决方法请更新 ////
标签: c++ dynamic pthreads multidimensional-array