2012-10-21 202 views
0

這裏是我有的代碼,它編譯和運行使用g ++,但我得到了分段錯誤。我知道它發生在pthread_join聲明的周圍,但我不知道爲什麼。爲什麼使用pthread_join時會出現分段錯誤?

#include <iostream> 
#include <stdio.h> 
#include <fstream> 
#include <pthread.h> 
#include <stdlib.h> 
#include <sstream> 

using namespace std; 

struct data{ 
    string filename; 
    int x; 
    int y; 
}; 

void *threadFunction(void *input){ 
    data *file = (data *) input; 
    string filename = file->filename; 
    ifstream myFile; 
    int xCount = 0; 
    int yCount = 0; 
    myFile.open(filename.c_str()); 
    string line; 
    while(myFile >> line){ 
     if(line == "X"){ 
      xCount++; 
     }else if(line == "Y"){ 
      yCount++; 
     } 
    } 
    file->x = xCount; 
    file->y = yCount; 
    return (void *) file; 
} 

int main(){ 
    pthread_t myThreads[20]; 
    data *myData = new data[20]; 

    for(int i = 0; i < 20; i++){ 
     ostringstream names; 
     names << "/filepath/input" << i+1 << ".txt"; 
     myData[i].filename = names.str(); 
     myData[i].x = 0; 
     myData[i].y = 0; 
    } 
    for(int i = 0; i < 20; i++){ 
     int check = pthread_create(&myThreads[i], NULL, threadFunction, (void *) &myData[i]); 
     if(check != 0){ 
      cout << "Error Creating Thread\n"; 
      exit(-1); 
     } 
    } 



    int xCount = 0; 
    int yCount = 0; 

    for(int i = 0; i < 20; i++){ 
     data* returnedItem; 
     pthread_join(myThreads[i], (void**) returnedItem); 
     xCount += returnedItem->x; 
     yCount += returnedItem->y; 
    } 

    cout << "Total X: " << xCount << "\n"; 
    cout << "Total Y: " << yCount << "\n"; 

} 

我沒有調用從我的threadFunction正確返回?我一直在嘗試一堆不同的東西,我仍然不知道發生了什麼......任何幫助將不勝感激! (文本文件我打開每行包含任何一個X或Y。我的目標是算在20個文本文件X和Y的總數)

回答

0

pthread_join第二個參數將被用來返回,線程的返回值,所以地方里面pthread_join我們有一個叫*secondArgument = thread_return_value代碼,但讓我們看看你在這裏做什麼:

// You are not initializing returnedItem, so it contain some garbage value 
// For example 0x12345678 
data* returnedItem; 
// Now you cast that garbage to (void**), and pthread_join will call 
// *(0x12345678) = thread_return_value that will cause segmentation fault 
pthread_join(myThreads[i], (void**) returnedItem); 

但你想要將返回值複製到returnedItem,對不對?如果你的回答是肯定的,你應該把地址returnedItem改爲pthread_join,這樣它就可以在那裏複製它。所以改變你的電話:

pthread_join(myThreads[i], (void**) &returnedItem); 
0
pthread_join(myThreads[i], (void**) returnedItem); 

應該

pthread_join(myThreads[i], (void**) &returnedItem); 

你」重新要求加入設置爲returnedItem的值爲void*您的線程函數返回...所以您需要給地址returnedItem

0

pthread_join()的第二個參數是要存儲結果的void**。但是,您傳遞的是隨機值。這可能倒是應該是這個樣子:

void* result; 
pthread_join(myThread[i], &result); 
data* returnedItem = static_cast<data*>(result); 

當然,這個假設一個data*,的確是回來了。