這裏是我有的代碼,它編譯和運行使用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的總數)