droly96 droly96 - 28 days ago 13
C++ Question

Segmentation Fault when running 3 threads

So I am creating 3 threads. 1 to read input from the user 1 to do some string manipulation, and 1 to write to the command prompt.

I have set up some

cout
statements to see where I am getting an error. I can see I am getting the error sometime after I create the threads.

I think it has to be something with which thread is executed first. I want the
readerThread
function to run first then the
converterThread
and finally the
writerThread
. I have been looking around for some way to implement more logic on these to restrict the order in which the threads run and can't find any.

Anyways here is my code:

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
int counter = 0;
vector<string> readBuffer;
vector<string> writeBuffer;
int main (){
int readerInt,writerInt,converterInt;
pthread_t reader,writer,converter;
cout << "BEFORE"<<endl;
readerInt = pthread_create(&reader, NULL,readerThread,NULL);
converterInt = pthread_create(&converter,NULL,converterThread,NULL);
writerInt = pthread_create(&writer,NULL,writerThread,NULL);
cout << "AFTER" << endl;

pthread_join(reader,NULL);
pthread_join(converter,NULL);
pthread_join(writer,NULL);

return 0;
}
void * readerThread(void *unused){
while(1){
pthread_mutex_lock(&lock);
string readLine;
getline(cin,readLine);
counter++;
readBuffer.push_back(readLine);
pthread_mutex_unlock(&lock);
}
}
void * converterThread(void *unused){
while(1){
pthread_mutex_lock(&lock);
if(readBuffer.size() > 0){
replace(readBuffer[counter-1].begin(),readBuffer[counter-1].end(),' ','%');
writeBuffer.push_back(readBuffer[counter-1]);
}
pthread_mutex_unlock(&lock);
}
}
void * writerThread(void *unused){
while(1){
pthread_mutex_lock(&lock);
cout << writeBuffer[counter-1] << endl;
pthread_mutex_unlock(&lock);
}
}

Answer

Your writerThread thread starts the job before the data arrived and you access:

cout << writeBuffer[counter-1] << endl;

when counter is still 0. You should check the size of writeBuffer before access.

counter variable is not always valid for writeBuffer. It happens when data is in readBuffer, but is not yet processed by converterThread.

You could remove counter variable usage and improve data structures for readBuffer and writeBuffer. Use std::queue to create queue for data conversion. One queue readBuffer for read data and one writeBuffer queue for processed results. Use push/pop methods.

Comments