2015-08-15 39 views
-1

我已經在幾個月的時間裏對我的大腦反對這個程序。這是我上一個學期上課的任務,而我通過後,我無法正確地完成這一項任務(Seg Fault)。我歡迎任何幫助或提示,但我非常感謝解釋和答案。C多線程wordcount程序段分割故障問題

該程序應該接收一個包含文件名列表的文件名(本例爲240)。這些文件位於與列表和程序相同的目錄中的文件夾中。這個程序應該把這個列表解析爲4個線程,爲每個線程平均分配文件名(每個線程60個例子)。然後每個線程獲取60個文件名的列表,並逐個打開每個文件,在每個文件上執行WordCount函數。一旦線程完成其任務,它們應該按照每個線程在其自己的塊中的順序打印每個文件的結果(即,線程1結果|線程2結果|線程3結果等等)。

我已經調試了一下,知道直到線程創建一切正常,因爲它應該。我的問題似乎是在線程啓動/執行期間。我已經嘗試在混音中添加互斥,但可悲的是它沒有幫助。我似乎錯過了一些東西或想到某些事情,因爲我的一些班級同學已經向我展示了他們更緊湊的代碼。請協助。謝謝!

這裏是主:

#include <pthread.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <time.h> 
#define MaxLine 200 
#define NUMTHREADS 4 

char Line[MaxLine]; 
pthread_mutex_t Lock = PTHREAD_MUTEX_INITIALIZER; 

typedef struct thread { 
    int id; 
    char file; 
}ThreadData; 

/* ThreadFunction will give each thread its processes to execute */ 
void *threadFunc (void *td) { 
    ThreadData *data = (ThreadData*)td; 
    int thread_num=data->id; 
    char filename=data->file; 
    printf("thread debug tid: %d and file: %c",thread_num, filename); 
    pthread_mutex_trylock(&Lock); 
    FILE *fn = fopen(filename, "r"); 
    if (fn == NULL) { 
     error("ERROR: Opening file"); 
     return 1; 
    } 
    while (fgets(Line, sizeof(Line), fn) != NULL) { 
     CountWord(thread_num, Line); 
    } 
    fclose(fn); 
    free(data); 
    pthread_mutex_unlock(&Lock); 
    pthread_exit(NULL); 
} 

int main(int argc, char *argv[]){ 
    char buf[20]; 
    int c, i, t, tnum, QUEUETOTAL; 
    pthread_t thread[NUMTHREADS]; 
    ThreadData td[NUMTHREADS]; 

    if (argc != 2){ 
     fprintf(stderr,"ERROR: Usage must be Countfile filename\n", argv[0]); 
     exit(0); 
    } 
    char const* const filename = argv[1]; 
    FILE* file = fopen(filename, "r"); 
    if (file == 0){ 
     printf("Could not open file!\n"); 
     exit(0); 
    } 

    /* Count iterations of while loop to divide files among threads. */ 
    while (fgets(Line, sizeof(Line), file)){ 
     QUEUETOTAL++; 
    } 

    /* Divide work for threads. */ 
    int thread2taskstart=(QUEUETOTAL/NUMTHREADS); //60 
    int thread3taskstart=(QUEUETOTAL/NUMTHREADS)*2; //120 
    int thread4taskstart=(QUEUETOTAL/NUMTHREADS)*3; //180 
    // QUEUETOTAL = 240 

    rewind(file); 
    FILE *tempfile1 = fopen("temp1.txt","w"); 
    for (i=0; i<thread2taskstart; i++) { 
     // populate tempfile1 with entries 1-60 
     if(fgets(Line,sizeof(Line),file)!=NULL) { 
      fputs(Line,tempfile1); 
      //printf("Debug temp1: %s",Line); 
     } 
    } 
    fclose(tempfile1); 
    FILE *tempfile2 = fopen("temp2.txt","w"); 
    for (i=thread2taskstart; i<thread3taskstart; i++) { 
     // populate tempfile2 with entries 60-120 
     if(fgets(Line,sizeof(Line),file)!=NULL) { 
      fputs(Line,tempfile2); 
      //printf("Debug temp2: %s",Line); 
     } 
    } 
    fclose(tempfile2); 
    FILE *tempfile3 = fopen("temp3.txt","w"); 
    for (i=thread3taskstart; i<thread4taskstart; i++) { 
     // populate tempfile3 with entries 120-180 
     if(fgets(Line,sizeof(Line),file)!=NULL) { 
      fputs(Line,tempfile3); 
      //printf("Debug temp3: %s",Line); 
     } 
    } 
    fclose(tempfile3); 
    FILE *tempfile4 = fopen("temp4.txt","w"); 
    for (i=thread4taskstart; i<=QUEUETOTAL; i++) { 
     // populate tempfile3 with entries 180-240 
     if(fgets(Line,sizeof(Line),file)!=NULL) { 
      fputs(Line,tempfile4); 
      //printf("Debug temp4: %s",Line); 
     } 
    } 
    fclose(tempfile4); 
    fclose(file); 

    /* Prepare parameters & launch (4) threads. Wait for threads 
    to finish & print out results as specified in assignment. */ 
    printf("Counting files …\n"); 

    for(t=0;t<NUMTHREADS;t++){ 
     tnum=t+1; 
     snprintf(buf, "temp%d.txt", tnum); 
     printf("debug tnum and array: %d and %s\n",tnum, buf); 
     td[t].id = tnum; 
     td[t].file = buf; 
     // Creates a new thread for each temp file. 
     pthread_create(&thread[t], NULL, threadFunc, td); 
    } 
    // Joins threads. 
    printf("debug: printing threads \n"); 
    for(t=0;t<NUMTHREADS;t++){ 
    pthread_join(thread[t], NULL); 
    printf("------------------------- Processes finished for Thread %d ----------------------- \n",t+1); 
    } 
    return 0; 
} 

這裏是COUNT函數:

#include <stdio.h> 

int CountWord(int tinfo, char cfile){ 
    int i; 
    int ccount = 0; 
    int wcount = 0; 
    int lcount = 0; 
    FILE *fname; 
    char fn[strlen(cfile) + 18]; 
    sprintf(fn, "./CountingFolder/%s", cfile); 
    printf("Debug: %s\n", fn); 
    fname = fopen(fn, "r"); 
    if (fname == NULL) { 
     error("ERROR: Opening file"); 
    } 
    while ((i = fgetc(fname)) != EOF){ 
     if (i == '\n') { 
      lcount++; 
     } 
     if (i == '\t' || i == ' '){ 
      wcount++; 
     } 
     ccount++; 
    } 
    printf("Threadid %d processes %s which has %d characters, %d words and %d lines\n", tinfo, cfile, ccount, wcount, lcount); 
    fclose(fname); 
    return 0; 
} 
+0

您正在使用'pthread_mutex_trylock'而不檢查結果。當它沒有獲得鎖定會發生什麼? – Kninnug

+0

in函數:CountWord():當文件無法打開時,請勿嘗試從文件 – user3629249

+0

讀取函數中的內容:CountWord():在'while'循環中:考慮輸入文件中的行包含一些標籤和空格不包含其他字符的組合,包括/特別是在行首。正確的文本在每個句子結束後有2個空格。建議:1)搜索stackoverflow中的例子(可能沒有多個線程)從文件中提取單詞。好例子將有一個兩字節的機器在字內和非字內執行。以非字內狀態開始。 – user3629249

回答

3

1)可能是一個錯字。但

int CountWord(int tinfo, char cfile){ .. }

應該

int CountWord(int tinfo, char *cfile){ .. } 

2)你是從main()傳球同樣buf所有線程。數據競爭和未定義的行爲。

3)snprintf()調用都不採用size參數。未定義的行爲。

4)由於所有線程都使用不同的數據,所以根本不需要鎖。你沒有分配td數組。所以你不能在線程函數中調用free(data);。未定義的行爲。

可能有更多的代碼問題,但段錯誤可能是因爲(3)或(5)。

+0

(4)雖然線程使用全局變量'Line'... – Kninnug

+0

對不需要使用鎖,因爲讀取行的變量是全局變量,但它應該是一個局部變量。 –

+0

@BlueMoon:全局變量不需要鎖定,爲什麼這麼做? –

0

在你的代碼在這裏

snprintf(buf, "temp%d.txt", tnum); 
printf("debug tnum and array: %d and %s\n",tnum, buf); 
td[t].id = tnum; 
td[t].file = buf; 

最後一行分配一個指針到這個結構

typedef struct thread { 
    int id; 
    char file; 
}ThreadData; 

file領域是不是應該char *file;?我在MSVC中沒有thread.h,所以我無法編譯它。當然,你有所有警告啓用??

+0

如果是這種情況,它應該編譯失敗。絕對有些奇怪的事情發生在這裏(可能缺乏深層複製),但這也可能是問題的一個問題。 –