2011-09-15 52 views
1

我在this exercise上稍微走了一步,不確定是否應該用我的更新後的代碼發佈答案,編輯我的原始帖子,或者提出一個新問題。如果我沒有遵循協議,請告知。多線程:什麼時候開始和退出線程

我到目前爲止所做的工作是在輸入文件中讀取並將所有整數賦值給一個數組。然後我將整數總數(索引)除以線程數(number_of_threads),以找到最佳的numbers_per_thread

然後,我創建一個while循環來增加數組中的所有數字,根據最佳numbers_per_thread分配每個數字塊。

prob_5.c

#include <stdio.h> 

int main(int argc, char *argv[]) { 
int i, j; 
FILE *fp; 
int values[15000]; 
char line[32]; 
int index = 0; 
int number_of_threads = 10; 
int numbers_per_thread; 

for (i = 1; i < argc; i++) { 
    fp = fopen(argv[i], "r"); 

    if (fp == NULL) { 
     fprintf(stderr, "cat: can't open %s\n", argv[i]); 
     continue; 
    } 

    while (fgets(line, sizeof(line), fp) != NULL && (index < 15000)) { 
     sscanf(line, "%d", &values[index]); 
     index++; 
    } 

    fclose(fp); 
} 

numbers_per_thread = index/number_of_threads; 

while (i < index) { 
    for (j = 0; (j < numbers_per_thread) && (i < index); j++) { 

     i++; 
     j++; 
    } 
} 

printf("%d\n", index); 

return 0; 
} 

我很困惑,我應該如何處理線程的啓動和停止。我應該在我的for(j = 0; ..)循環中啓動它,然後創建一個if(j == numbers_per_thread)來結束線程?我應該創建一個新的數組來容納每個線程的數字塊嗎?我想我只是混淆瞭如何使用pthread_create,pthread_join等,因爲這是我第一次嘗試使用它們。

回答

0

我會製作一個pthread_t值的數組來存儲您創建的每個線程的ID。在讀取數組值後,在循環中創建它們,然後立即執行另一個循環以將它們全部加入。在此之後,你可以把個人的部分款項加起來,以得到你的最終金額。

+0

感謝您的建議。我已經添加了pthread_t線程[number_of_threads]並創建了這個循環:for(i = 0; i raphnguyen