I am a newbie in c++ working on what should be a pretty basic file read and then process data functionality and I keep getting stuck on being able to at least provide a “state” of on thread to another so that data could be consumed. This just maybe something really basic that I am overlooking – could use some insight into using pthreads in c++.
Bellow is some basic extracted code that functions OK, reads the file and provides data to be processed. Another thread that will process the data needs to know the state of this one.
What would be the best strategy? I am attempting to request the state of the thread through a function from another thread but receive incorrect response.
Reader::Reader(){
_threadId = 1;
_msg = NONE; // enum NONE, READ, STOP
active = false;
pthread_mutex_init(&_mutex, 0);
}
Reader::~Reader(){
pthread_mutex_destroy(&_mutex);
}
void Reader::read(){
_msg = READ;
active = true;
pthread_create(&_threadId, 0, work, this);
}
void * Reader::work(void *myselfreader){
Reader * reader = (Reader*)myselfreader;
reader->loop();
pthread_exit(0);
return 0;
}
void Reader::loop(){
while(active){
pthread_mutex_lock(&_mutex);
switch(_msg){
case READ:
// do the reading of the IO file - which works fine
// once done reading the file - the _msg is set to STOP
break;
case STOP:
stopThread();
break;
default:
break;
}
pthread_mutex_unlock(&_mutex);
}
return;
}
void Reader::stopThread(){
active = false;
_msg = ENC_NONE;
pthread_join(_threadId, 0);
}
/*****************/
int Reader::getReaderState(){
// another thread needs to know the state of this thread
//
return _msg // ??
return active // ??
}
It seems that you have race condition somewhere in your code.
You need to protect your
_msgvariable with mutex. Every time you need to update_msgvariable request mutex, update variable and close the mutex. You need to do the same thing for the reading ingetReaderState()function – acquire mutex, copy variable into temp, release mutex and return temp variable.For easy and error-prone usage, you should create getter and setter function for accessing
_msgfield which will be guarded by the same mutex (and not the one that you are already using):