2010-11-04 64 views
3

我有一个矩阵乘法代码,通过以下 乘法做矩阵,矩阵A *矩阵B =矩阵C多线程矩阵乘法帮助用C

for(j=1;j<=n;j++) { 
for(l=1;l<=k;l++) { 
    for(i=1;i<=m;i++) { 
    C[i][j] = C[i][j] + B[l][j]*A[i][l]; 

} 
} 

现在我想将它变成多线程矩阵乘法我的代码如下:

我使用结构

struct ij 
{ 
int rows; 
int columns; 
}; 

我的方法是

void *MultiplyByThread(void *t) 
{ 
struct ij *RowsAndColumns = t; 
double total=0; 
int pos; 
for(pos = 1;pos<k;pos++) 
{ 
    fprintf(stdout, "Current Total For: %10.2f",total); 
    fprintf(stdout, "%d\n\n",pos); 
    total += (A[RowsAndColumns->rows][pos])*(B[pos][RowsAndColumns->columns]); 
} 
D[RowsAndColumns->rows][RowsAndColumns->columns] = total; 
pthread_exit(0); 

} 

,并在我的主要是

 for(i=1;i<=m;i++) { 
     for(j=1;j<=n;j++) { 

    struct ij *t = (struct ij *) malloc(sizeof(struct ij)); 
    t->rows = i; 
    t->columns = j; 

    pthread_t thread; 
    pthread_attr_t threadAttr; 
    pthread_attr_init(&threadAttr); 
    pthread_create(&thread, &threadAttr, MultiplyByThread, t);  
    pthread_join(thread, NULL);  

     } 
     } 

但我似乎无法得到相同的结果作为第一矩阵乘法(这是正确的) 可有人点我到正确的方向?

回答

0

实际上,您的线程代码不是线程化的。您创建一个线程并在调用create之后通过调用联接等待它完成。您必须创建一个mxn线程矩阵,将其全部启动,然后将它们全部加入。除此之外,代码似乎与循环计算相同。结果与确切的差异是什么?

实施例(注意,不是编译):

pthread_t threads[m][n]; /* Threads that will execute in parallel */ 

,然后在主:

for(i=1;i<=m;i++) { 
    for(j=1;j<=n;j++) { 

    struct ij *t = (struct ij *) malloc(sizeof(struct ij)); 
    t->rows = i; 
    t->columns = j; 

    pthread_attr_t threadAttr; 
    pthread_attr_init(&threadAttr); 
    pthread_create(thread[i][j], &threadAttr, MultiplyByThread, t);  
    } 
    } 

    /* join all the threads */ 
    for(i=1;i<=m;i++) { 
    for(j=1;j<=n;j++) { 
     pthread_join(thread[i][j], NULL); 
    } 
    } 

(或多或少,只是不调用pthread_join用于在循环内的每个线程)。

+0

结果出来不一样。你加入他们的意思是什么?我以为那是我在做什么。你可以给我一个例子吗? – Kevin 2010-11-04 16:53:49

+0

这给了我一个分段错误。我不知道为什么? – Kevin 2010-11-04 17:07:34

+0

此外,我不认为这些线程应该是双数组本身。我相信一个线程应该在列中是单一的,然后结合在一起? – Kevin 2010-11-04 17:09:18

2

尝试以下操作:

#pragma omp for private(i, l, j) 
for(j=1;j<=n;j++) { 
    for(l=1;l<=k;l++) { 
     for(i=1;i<=m;i++) { 
      C[i][j] = C[i][j] + B[l][j]*A[i][l]; 
     } 
    } 
} 

虽然谷歌搜索的GCC编译器开关来启用OpenMP,我竟然横跨this blog post描述发生了什么比我更好,而且还包含一个更好的例子来。

对于多核机器,大多数合理相关的编译器都支持OpenMP,请参阅OpenMP web site以获取更多信息。