2012-10-05 60 views
1

我想使用pthreads乘以兩個矩陣。對於矩陣中的每個元素,將創建一個單獨的線程。在我的程序中,我這樣做了,但是使用了一個pthread_t數組,動態聲明它是兩個矩陣中元素總數的大小。Pthreads數組

我遇到的問題是我創建的線程很好,但作爲我的跑步者功能的測試,我有一個似乎不執行一次的cout語句。爲了簡潔起見,我刪除了從文件中讀取兩個矩陣的代碼部分,並將它們存儲到兩個數組中。它還計算了兩個矩陣中元素的數量,並用它來設置pthread數組的大小。我已經單獨測試了這些代碼,所以我很確定它與我的問題無關。

這裏是代碼關於我的問題:

int main(int argc, char **argv) 
{ 
pthread_attr_t attr; 
pthread_t *workers; 
workers = new pthread_t[numThreads]; 
int counter = 0; 
for(int count1 = 0; count1 < (rows2 * cols2); count1++) 
{ 
    infile2 >> array2[count1]; 
} 
for(int i = 0; i < rows1; i++) 
{ 
    for(int j = 0; j < cols1; j++) 
    { 
     location *data = new location; 
     data->row = i; 
     data->col = j; 
     pthread_create(&(workers[counter]), &attr, runner, data); 
     counter++; 
    } 
} 
for(int i = 0; i < rows2; i++) 
{ 
    for(int j = 0; j < cols2; j++) 
    { 
     location *data = new location; 
     data->row = i; 
     data->col = j; 
     pthread_create(&(workers[counter]), &attr, runner, data); 
     counter++; 
    } 
} 
for(int add = 0; add < 24; add++) 
{ 
    pthread_join(workers[add], NULL); 
} 
return 0; 
} 

和我的轉輪功能:

void *runner(void *param) 
{ 
    cout << "bob" << endl; 
    pthread_exit(NULL); 
} 

回答

2

你在你的實際代碼初始化pthread_attr地方?如果不使用pthread_attr_init(),或者如果不使用它,則將其作爲NULL傳遞。它看起來像pthread_create與「無效參數」失敗。此外,如果您在真實代碼中尚未這樣做,請檢查所有返回代碼。 Pthread參數在成功時返回0,失敗時返回正整數。

+0

是的,這解決了問題。我改變了我傳遞attr函數的部分爲NULL並且cout語句起作用。 – Wenadin