2013-10-12 66 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