2013-10-12 65 views
0

当我使用pthread_join()时,我不确定它是否在正确的位置。就像现在这样,它是否会等待线程退出,然后再次循环遍历循环?我想我问的是我应该把它从double for循环中取出来,然后直接在pthread_join()之后创建一个新的for循环? PS:我对一般的线程和C语言都很陌生。我还有另一个关于释放malloc的东西的问题(在代码中作为注释)。我不确定在哪里使用free关键字,因为malloc结果指针在for循环的每次迭代后都消失了。pthread_join()是否会导致顺序执行?

这是我的代码。它用于两个预定义矩阵上的矩阵乘法(A & B)。 (这是老师希望我们做的)。

#include<stdio.h> 
#include<stdlib.h> 
#include<pthread.h> 

#define M 3 
#define K 2 
#define N 3 

int A[M][K] = {{1,4}, {2,5}, {3,6}}; 
int B[K][N] = {{8,7,6}, {5,4,3}}; 
int C[M][N]; 

struct coords 
{ 
    int i ; /* row */  
    int j ; /* column */ 
}; 

//thread function 
void* calc_val(void* resultCoords) 
{ 
    int n, result = 0; 
    struct coords **matCoords = (struct coords**) resultCoords; 
    for(n = 0; n < K; n++) 
    { 
     result += A[(*matCoords)->i][n] * B[n][(*matCoords)->j]; 
    } 
    C[(*matCoords)->i][(*matCoords)->j] = result; 
    // One more question: 
    // <- Should I free mem from malloc here? 
} 

int main(int argc, char** argv) 
{ 
    int numThreads = M * N, threadIndex = 0, i, j; 
    pthread_t threads[numThreads]; 
    pthread_attr_t attributes[numThreads]; 
    for (i = 0; i < M; i++) 
    { 
     for(j = 0; j < N; j++) 
     { 
      struct coords *data = (struct coords*)malloc(sizeof(struct coords)); 
      data->i = i; 
      data->j = j; 
      pthread_attr_init(&attributes[threadIndex]); 
      pthread_create(
        &threads[threadIndex], 
        &attributes[threadIndex], 
        calc_val, 
        &data); 
      pthread_join(threads[threadIndex], NULL); // <-Main Question 
      threadIndex++; 
     } 
    } 

    /* ... */ 

    return (EXIT_SUCCESS); 
} 

回答

0

在你的代码基本上看下面:

  1. 准备一些数据线
  2. 运行线程
  3. 等待,直到它完成
  4. 进入下一次迭代

所以这段代码绝对连续

使其成为非连续的,你需要的是这样的:

  1. 准备一些数据
  2. 运行线程
  3. 进入下一次迭代
  4. 等待,直到所有线程都完成

试试这样的:

for (i = 0; i < M; i++) 
    { 
     for(j = 0; j < N; j++) 
     { 
      struct coords *data = (struct coords*)malloc(sizeof(struct coords)); 
      data->i = i; 
      data->j = j; 
      pthread_attr_init(&attributes[threadIndex]); 
      pthread_create(&threads[threadIndex], &attributes[threadIndex], calc_val, &data); 
      threadIndex++; 
     } 
    } 
    for (i=0;i<numThreads;i++) 
     pthread_join(threads[i], NULL); 

关于内存分配的下一个问题 - 你可以做到这一点无论是在所有线程都完成(那么你需要在一些地方保存所有分配的指针),或者你可以在它的每个线程只是免费为您的评论

+0

问哇,感谢您的快速反应 - 您的真棒!这正是我正在寻找的答案。这有助于我现在更好地理解pthread_join。编辑:为释放malloc - 我尝试了它的线程函数,但得到了奇怪的结果,但你的第一个建议像魅力一样工作。 – willko747

+0

免费试用(resultCoords)或免费试用(matCoords)?第一个应该只工作 –

+0

噢好吧。是的,我尝试免费(* matCoords); – willko747