Here is the code I have, it compiles and runs using g++ but I get a segmentation fault. I know it happens around the pthread_join statement but I cant figure out why.
#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";
}
Am I not calling return properly from my threadFunction? I’ve been trying a bunch of different things and I still don’t know what’s going on…any help would be greatly appreciated! (the text file I open contain either an X or Y per line. My goal is to count the total number of Xs and Ys in 20 text files)
Second argument of
pthread_joinwill be used to return, return value of the thread, so somewhere insidepthread_joinwe have a code that call*secondArgument = thread_return_value, but lets look at what you are doing here:But you want return value to be copied to
returnedItem, am I right? in case that you answer is yes you should pass address ofreturnedItemtopthread_joinso it can copy it there. So change your call to: